简体   繁体   中英

Javascript array weird behavior

Ok, when write like below:

var element = { "name": "" };

var array = [];

for (var i = 0; i < 2; ++i) {
    var newelement = element;
    newelement.name = i.toString();
    array[i] = newelement;
}    

Result in:array[0].name == array[1].name == "1". But write in another way:

var element = { "name": "" };

var array = [];

for (var i = 0; i < 2; ++i) {
    var newelement = { "name": i.toString() };
    array[i] = newelement;
}

Result in:array[0].name == "0" and array[1].name == "1".

Tell me why.

因为在第二个示例中,您在每次迭代时创建一个新对象,但在第一个示例中,您始终引用相同的元素。

This is a good Javascript question for people to encounter and understand.

In the first block of code, you are assigning newelement a reference to element . Each time through the loop, newelement gets the same reference assigned to it. You aren't creating any new objects, just assigning the same one over and over again.

In the second block of code, you are creating a new object inside the loop so each assignment goes to a different object.

You need to remember that in javascript, assigning an object to a variable only assigns a reference to that object.

var newelement = element;   // just assigns a reference to an existing object

Yet, assigning like this is creating a new object:

var newelement = { "name": i.toString() };   // creates a new object

So, in the first code sample, you have array[0] and array[1] each with a reference to the same object. When you modify that object, it affects both array[0] and array[1] since they are both pointing at that object.

In the second code sample, array[0] and array[1] are each pointing at a different object so when you modify one, it does not affect the other.

This is a tricky part of javascript and is something that often trips up C/C++ programmers (it certainly got me when I was first learning JS) who are use to something like the first assignment being a structure copy. Javascript defaults to just assigning a reference unless you're using syntax that specifically creates a new object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM