对象是否以javascript的深层或浅层副本推入数组?


74

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

Answers:


137

这取决于您要推动什么。对象和数组被推为指向原始对象的指针。内置的原始类型(如数字或布尔值)将作为副本推送。因此,由于不以任何方式复制对象,因此没有深层或浅层副本。

这是显示它的工作片段:

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

45

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.

2
关于new“断开连接”对象引用的有趣观点。
特拉维斯J

2
下注解释?如果您不让我知道那是什么,很难解决该问题。
鲁芬

为什么要ping我?很久以前,我对此表示赞同,并喜欢您的回答。这是投票画面:i.imgur.com/AnDt98c.png
Travis J

1
抱歉@Travis-SO的附带损害,我没有其他方法可以与最近一两周来的最近匿名匿名投票者交流。我没想到它来自你,特别是。与您的正面评论。对不起,您很不幸收到了垃圾邮件,并感谢您关注我们的问题!
ruffin

1
这实际上是我的误解。我的错。您的评论显示在我的通知中,我认为这是针对我的,因为我没有意识到作为OP,所有评论都显示为通知。
特拉维斯J
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.