赞
踩
Object.assign(target,source)
Object.assign方法主要用于对象的合并,将 源对象 的所有可枚举属性 复制到 目标对象,并返回目标对象。
它至少需要两个对象作为参数:target是目标对象,后面的参数都是源对象。
let target1={
name:'小红'
}
let source1={
sex:'女'
}
let source2={
age:'26'
}
console.log(Object.assign(target1,source1,source2))
// 输出--- {name: "小红", sex: "女", age: "26"}
let targetObj1 = { a: 10, b: 20 };
let sourceObj1 = { b: 100};
let sourceObj11 = { c: 30 };
Object.assign(targetObj1, sourceObj1, sourceObj11);
console.log(targetObj1);
// 输出--- {a: 20, b: 100, c: 30}
注:如果有多个源对象的话,没有同名的属性会直接复制到目标对象上,如果有同名属性的话,后面的属性值会覆盖前面的属性值。
console.log(Object.assign(null)) // 报错
let target = { a: { b: 'c', d: 'e' } }
let source = { a: { b: 'hellow world' } }
Object.assign(target, source)
console.log(target)
// 输出--- {a: {b: "hello world"}}
注:上面代码中,target对象的a属性被source对象的a属性整个替换掉了,而不会得到{ a: { b: ‘hello’, d: ‘e’ } }的结果。这通常不是开发者想要的,需要特别小心。有一些函数库提供Object.assign的定制版本(比如Lodash的_.defaultsDeep方法),也可以解决深拷贝的问题。
console.log(Object.assign([1, 2, 3], [4, 5]));
// 输出--- 其中,4覆盖1,5覆盖2,因为它们在数组的同一位置,所以就对应位置覆盖了。
// 输出--- [4,5,3]
转载请注明原作者
不喜勿喷,欢迎补充~~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。