2011-12-28 94 views

回答

100

这取决于你在推什么。对象和数组被作为指向原始对象的指针推送。像数字或布尔值这样的内置原始类型会作为副本推送。所以,由于对象没有以任何方式复制,因此它们没有深度或浅度的副本。

这里有一个工作片断显示它:

var array = []; 
 
var x = 4; 
 
var 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

30

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. 
+0

有关使用'new'到 “断开” 的对象参考有趣的观点。 – 2013-02-08 18:51:02

+1

Downvote解释?如果你不让我知道它是什么,很难解决这个问题。 – ruffin 2013-11-03 01:44:00

+0

为什么要ping我?我很久以前就提出了这个建议,并且喜欢你的答案。以下是投票屏幕:http://i.imgur.com/AnDt98c.png – 2013-11-03 06:14:43