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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (16)

当在javascript中使用.push()数组时,是否将对象推入数组中的指针(浅)或实际对象(深),而不考虑类型。

提问于
用户回答回答于

这取决于你在推什么。对象和数组通过引用推送。像数字这样的内置类型被作为副本推送。这是一个显示它的工作片段:

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

用户回答回答于

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.

扫码关注云+社区