简体   繁体   English

javascript for 循环对象修改,数组插入

[英]javascript for loop object modify, array insert

why it's not adding 1,2,3,4为什么不加 1,2,3,4

var arr = [];
var obb = {view: [], add: []};
for(var i = 0; i < 5;i++) {
    obb.view = i;
    obb.add = i;
    arr.push(obb); 
}

Instead every obb value is the very last one, why and what can i do about it?相反,每个 obb 值都是最后一个,为什么以及我能做些什么?

You are declaring arrays inside your object which doesn't make any sense since you have an approach of assigning only one integer inside one array and then in the other same reference object you are again adding only one number to it and so on...你在你的对象中声明数组,这没有任何意义,因为你有一种方法是在一个数组中只分配一个整数,然后在另一个相同的引用对象中你再次只向它添加一个数字,依此类推......

Here is a working example with you approach:这是您的方法的一个工作示例:

var arr = [];
var obb = 
{
    view: [],
    add: []
};
for (var i = 0; i < 5; i++) {
    obb.view = i;
    obb.add= i;
    arr.push(obb);
    alert(arr[i].view);
    alert(arr[i].add);
}

However this is the same thing (using object literal again) but without arrays since you don't need them:但是,这是同一件事(再次使用对象文字)但没有数组,因为您不需要它们:

var obb = 
{
    view:0,
    add:0
};

The rest of the code stays the same.其余代码保持不变。

The best thing would to to populate the array which is inside the object and then call the object array by index:最好的办法是填充对象内部的数组,然后按索引调用对象数组:

var obb = 
{
    view: [],
    add: []
};
for (var i = 0; i < 5; i++) {
    obb.view[i] = i;
}

alert(obb.view[index]);

Last example:最后一个例子:

for (var i = 0; i < 5; i++) {
    obb.view[i] = i;
    arr.push(obb);
    alert(arr[i].view);
}

I think this example is good for learning because it demonstrates the behaviour of objects.我认为这个例子有利于学习,因为它演示了对象的行为。 The array inside the object is being populated after every iteration and the same object is pushed inside another array as well.每次迭代后都会填充对象内部的数组,并且将同一对象也推送到另一个数组中。 Since we are dealing with the same object you can see that if you call the object (depending on the index) you will see that values are being accumulated.由于我们正在处理同一个对象,因此您可以看到,如果您调用该对象(取决于索引),您将看到正在累积值。 For example arr[4].view will output :0,1,2,3,4 because of the same object but with values which were added in the array in every iteration.例如 arr[4].view 将输出 :0,1,2,3,4 因为相同的对象,但在每次迭代中都会在数组中添加值。

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

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