将对象推入javascript深层或浅层副本中的数组?

Tra*_*s J 67 javascript arrays push

非常明显的问题......在javascript中对数组使用.push()时,无论类型如何,对象都会将指针(浅)或实际对象(深)推入数组.

jfr*_*d00 123

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

这是一个显示它的工作片段:

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
Run Code Online (Sandbox Code Playgroud)

  • 吹毛求疵:每个值都被推送*作为一个值*;对于对象来说,这些值恰好是指向该对象的“指针”。 (2认同)

ruf*_*fin 37

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.
Run Code Online (Sandbox Code Playgroud)

  • 关于使用“ new”“断开”对象引用的有趣观点。 (2认同)
  • 下注解释?如果您不让我知道那是什么,很难解决该问题。 (2认同)
  • 抱歉@Travis——附带损害,因为我没有其他方式与最近一两周内出现的匿名反对者进行沟通。我没想到它来自你,尤其是。与您的积极评价。很抱歉给您带来了不幸的垃圾邮件,感谢您继续关注您的问题! (2认同)
  • 这其实是我的一个误会。我的错。您的评论显示在我的通知中,我认为它是针对我的,因为我没有意识到作为OP,所有评论都显示为通知。 (2认同)