本人初学者,在学习的过程中遇到了一个深拷贝相关的问题,JS代码如下:
let personArr = [],
allPerson = [],
data = [{//初始数据
name: "bill",
age: 19
}, {
name: "tom",
age: 20
}]
function Person(obj) { //对象构造函数
let val;
for (let key in obj) {
val = obj[key];
this[key] = val;
}
}
for (let i = 0, len = data.length; i < len; i++) {
let temp;
temp = new Person(data[i]);//循环创建对象
personArr = personArr.concat(temp);//将对象合并入对象数组 注:查阅相关资料concat
}
$.extend(true, allPerson, personArr);//jQuery深拷贝对象数组
console.log(personArr[0].name);//输出bill
console.log(allPerson[0].name);//输出bill
personArr[0].name = "test"; //修改属性
console.log(personArr[0].name);//输出test
console.log(allPerson[0].name);//输出test
并没有想我预期的那样成功深拷贝了每一个对象,从输出值可以看出两个对象数组之间还是存在联系,我试过使用jQuery的extend方法深拷贝一个对象字面量形式存放的对象数组,如:
[{
name: "bill",
age: 19
}, {
name: "tom",
age: 20
}]
在这种情况下修改personArr中的对象属性,allPerson不会随之变化,我很疑惑,出现这种情况的原因是什么?该如何解决?经过下午的尝试我猜测问题是在temp = new Person(data[i]);这一步上,是不是new的对象可能只是一个指向目标对象的指针?求高人指点
codepen:https://codepen.io/Vincedd/pr...
Looked at the jquery.extend source code
You can find that it is false when judging jquery.isPlainObject(copy);
That is, personArr[0] is not a pure object (that is, the literal or the constructor is Object)
What is executed at this time is
is a reference to the object