我们使用Object.assign(target,…sources)时,其实只是浅拷贝。只能复制第一层属性,而如果第一层属性中有对象或数组的话,其实只是对对象或数组的引用而已。
我们修改target里的对象属性时,source对象中对应的对象属性也会改变
let source = {
age: 'nice',
obj: {
name: 'nice'
}
}
let target = {
}
Object.assign(target, source)
target.obj.name = 'change'
console.log(target.obj.name) //change
console.log(source.obj.name) //change
要想实现深拷贝:
function deepCopy(target, source) {
if (source == null) {
return
}
for (let i in source) {
if (Object.prototype.hasOwnProperty.call(source, i)) {
console.log(i)
console.log(typeof i)
if