gpt4 book ai didi

javascript - 将对象插入 javascript 深拷贝还是浅拷贝中的数组?

转载 作者:IT王子 更新时间:2023-10-29 02:51:33 26 4
gpt4 key购买 nike

非常不言而喻的问题...在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com