做对象推入数组在javascript深或浅复制

Do objects pushed into an array in javascript deep or shallow copy?

本文关键字:复制 javascript 对象 数组      更新时间:2023-09-26

很明显的问题…当在javascript中对数组使用.push()时,被推入数组的对象是指针(浅)还是实际对象(深),而不管类型为。

这取决于你在推什么。对象和数组作为指向原始对象的指针被压入。内置基本类型(如数字或布尔值)被作为副本压入。因此,由于对象不以任何方式复制,因此它们不存在深复制或浅复制。

下面是显示它的工作代码片段:

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

jfriend00在这里是正确的,但是有一点需要澄清:这并不意味着您不能更改变量指向的内容。也就是说,y最初引用了您放入数组中的一些变量,但是您可以使用名为y的变量,将其从现在数组中的对象断开,并连接y(即使其引用)完全不同的东西,而不改变现在仅由数组引用的对象。

http://jsfiddle.net/rufwork/5cNQr/6/

var array = [];
var x = 4;
var y = {name: "test", type: "data", data: "2-27-2009"};
// 1.) pushes a copy
array.push(x);
x = 5;
document.write(array[0] + "<br>");    // alerts 4 because it's a copy
// 2.) pushes a reference
array.push(y);
y.name = "foo";
// 3.) Disconnects y and points it at a new object
y = {}; 
y.name = 'bar';
document.write(array[1].name + ' :: ' + y.name + "<br>");   
// alerts "foo :: bar" because y was a reference, but then 
// the reference was moved to a new object while the 
// reference in the array stayed the same (referencing the 
// original object)
// 4.) Uses y's original reference, stored in the array,
// to access the old object.
array[1].name = 'foobar';
document.write(array[1].name + "<br>");
// alerts "foobar" because you used the array to point to 
// the object that was initially in y.

JavaScript:在2023创建一个对象的深度拷贝

不要在JavaScript中使用Object.assign()来复制或克隆对象!创建对象的浅拷贝,并将深拷贝中的对象赋值给引用指针!

你有两个选择

使用旧的、更可靠的JSON技巧:

const obj1 = JSON.parse(JSON.stringify(YourObject));

或者试试新的&改进的structuredClone()方法。警告:这只适用于自2022以来更新了常绿浏览器的用户!不支持Internet ExplorerEdge Trident浏览器!!

const obj2 = structuredClone(YourObject);