非常不言而喻的问题...在 javascript 中对数组使用 .push() 时,插入数组的对象是指针(浅)还是实际对象(深)不管类型。
最佳答案
这取决于您要推送的内容。对象和数组作为指向原始对象的指针被推送。内置原始类型(如数字或 bool 值)作为副本推送。因此,由于不以任何方式复制对象,因此它们没有深拷贝或浅拷贝。
这是一个显示它的工作片段:
var array = [];
var x = 4;
let y = {name: "test", type: "data", data: "2-27-2009"};
// primitive value pushes a copy of the value 4
array.push(x); // push value of 4
x = 5; // change x to 5
console.log(array[0]); // array still contains 4 because it's a copy
// object reference pushes a reference
array.push(y); // put object y reference into the array
y.name = "foo"; // change y.name property
console.log(array[1].name); // logs changed value "foo" because it's a reference
// object reference pushes a reference but object can still be referred to even though original variable is no longer within scope
if (true) {
let z = {name: "test", type: "data", data: "2-28-2019"};
array.push(z);
}
console.log(array[2].name); // log shows value "test" since the pointer reference via the array is still within scope
关于javascript - 将对象插入 javascript 深拷贝还是浅拷贝中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8660901/