简体   繁体   English

Javascript数组奇怪的行为

[英]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". 结果: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". 结果:array [0] .name ==“0”和array [1] .name ==“1”。

Tell me why. 告诉我为什么。

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

This is a good Javascript question for people to encounter and understand. 这是一个很好的Javascript问题,供人们接触和理解。

In the first block of code, you are assigning newelement a reference to element . 在第一个代码块中,您newelement分配对element的引用。 Each time through the loop, newelement gets the same reference assigned to it. 每次循环时, newelement都会获得分配给它的相同引用。 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. 您需要记住,在javascript中,将对象分配给变量只会分配对该对象的引用。

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. 因此,在第一个代码示例中,您有array[0]array[1]每个都引用了同一个对象。 When you modify that object, it affects both array[0] and array[1] since they are both pointing at that object. 修改该对象时,它会同时影响array[0]array[1]因为它们都指向该对象。

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. 在第二个代码示例中, array[0]array[1]分别指向不同的对象,因此当您修改一个对象时,它不会影响另一个对象。

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的一个棘手的部分,并且经常绊倒C / C ++程序员(当我第一次学习JS时它确实得到了我),他们正在使用像第一个作为结构副本的东西。 Javascript defaults to just assigning a reference unless you're using syntax that specifically creates a new object. 除非您使用专门创建新对象的语法,否则Javascript默认只分配引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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