简体   繁体   English

Javascript:在循环中,修改对象的属性,然后推送到数组

[英]Javascript: In a loop, modify property of object then push to array

I have the following code (which works correctly): 我有以下代码(可以正常工作):

var arr = [];
for(var i = 0; i < 2; i++) {
    var obj = { a: 'A'};
    obj.c = 'C' + i;
    arr.push(obj);
}

// now arr is:
// [ {a: 'A', 'c': 'C0'}, {a: 'A', 'c': 'C1'} ]

To improve the performance of my code, I placed the obj outside the loop, then adding/modifying the new property only, like this: 为了提高代码的性能,我将obj放置在循环之外,然后仅添加/修改了新属性,如下所示:

var arr = [];
var obj = { a: 'A'};
for(var i = 0; i < 2; i++) {
    obj.c = 'C' + i;
    arr.push(obj);
}

// now arr is:
// [ {a: 'A', 'c': 'C1'}, {a: 'A', 'c': 'C1'} ]

Why both objects got C1 ? 为什么两个对象都获得C1? Please explain what I'm doing wrong, and how to place the object out of the loop and get correct results? 请说明我在做什么错,以及如何将对象置于循环之外并获得正确的结果?

Note : I know this is a simple problem where performance is not an issue, but I'm actually dealing with big number of objects in reality where performance matters. 注意 :我知道这是一个简单的问题,其中性能不是问题,但实际上在性能很重要的情况下,我实际上要处理大量对象。

You are pushing the object ( not a copy of the object) to the array, and then changing it. 您正在将对象( 不是对象的副本 )推送到数组,然后对其进行更改。

If you want different objects in each index, then you need to create a new object each time you go around the loop. 如果要在每个索引中使用不同的对象,则每次循环时都需要创建一个新对象。

Like the others wrote, you are changing the same object (the original) all the time which ends in the results being the same (the original). 就像其他人一样,您一直都在更改同一对象(原始对象),最终结果是相同的(原始对象)。

To place the object out of the loop and still get the correct result, you would still have to 'copy' it inside of the loop: 要将对象放置在循环外并仍然获得正确的结果,您仍然必须在循环内“复制”它:

var arr = [];
var obj = { a: 'A'};
var objstring = JSON.stringify(obj);
for(var i = 0; i < 2; i++) {
    var obj = JSON.parse(objstring);
    obj.c = 'C' + i;
    arr.push(obj);
}

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

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