【发布时间】:2012-01-29 11:03:23
【问题描述】:
相当不言自明的问题...当在 javascript 中的数组上使用 .push() 时,推入数组的对象是指针(浅)还是实际对象(深)不管输入。
【问题讨论】:
标签: javascript arrays push
相当不言自明的问题...当在 javascript 中的数组上使用 .push() 时,推入数组的对象是指针(浅)还是实际对象(深)不管输入。
【问题讨论】:
标签: javascript arrays push
这取决于你要推动什么。对象和数组作为指向原始对象的指针被推送。内置的原始类型(如数字或布尔值)作为副本推送。因此,由于对象不会以任何方式复制,因此它们没有深拷贝或浅拷贝。
这是一个显示它的工作 sn-p:
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
【讨论】:
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.
【讨论】:
new“断开”对象引用的有趣点。