[英]Do objects pushed into an array in javascript deep or shallow copy?
很明顯的問題...當在javascript中的數組上使用.push()時,對象是指針(淺)還是實際對象(深)推入數組, 而不管類型如何 。
這取決於您要推動什么。 對象和數組被推為指向原始對象的指針。 內置的原始類型(如數字或布爾值)將作為副本推送。 因此,由於不以任何方式復制對象,因此沒有深層或淺層副本。
這是顯示它的工作片段:
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.
我們可以通過json stringify傳遞對象/數組來清除指針,然后解析
newobj.push(JSON.parse(JSON.stringify(obj)));
我希望它對某人有幫助,因此我發布了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.