在javascript深度或浅拷贝中将对象推入数组中?

漂亮的自我明显的问题…当在JavaScript中的数组上使用.push()时,对象被推入数组中的指针(浅)或实际对象(深), 而不pipetypes。

这取决于你在推什么。 对象和数组是通过引用推送的。 像数字这样的内置types被作为副本推送。

var array = []; var x = 4; var y = {name: "test", type: "data", data: "2-27-2009"}; // primitive value pushes a copy array.push(x); x = 5; alert(array[0]); // alerts 4 because it's a copy // object reference pushes a reference array.push(y); y.name = "foo"; alert(array[1].name); // alerts "foo" because it's a reference 

此代码的工作演示: http : //jsfiddle.net/jfriend00/5cNQr/

jfriend00在这里的标志是正确的,但一个小的澄清:这并不意味着你不能改变你的variables指向。 也就是说, y最初引用了一些放入数组的variables,但是您可以使用名为y的variables,将其与数组中的对象断开连接,并将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.