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] = newelem开发者_运维知识库ent;
}
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.
Because in the second example you are creating a new object on each iteration, but in the first example you are referencing always the same element.
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.
精彩评论