javascript 如何增加对象变量内的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25877003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:09:15  来源:igfitidea点击:

How to increment a value inside an object variable

javascriptvariables

提问by Swift

I have the following.

我有以下内容。

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i <totalPeople; i++) {
   person[i] = dataset; 
}

Why i chose this approach, click here .

为什么我选择这种方法,请单击此处。

I'm trying to make one of the values auto increment inside another forloop.

我正在尝试使另一个for循环中的值之一自动递增。

I've tried the following approaches to no avail.

我尝试了以下方法无济于事。

person[1]{val1 : 0,
          val2 : 0,
          val3 : val3 + 1};

person[1]{val1 : 0,
          val2 : 0,
          val3 : person[1].val3 + 1};

person[1].val3 = person[1].val3 + 1;

any ideas?

有任何想法吗?

采纳答案by Gerald

Totally sorry. The solution that you're referring to herewas posted by me and is incorrect. I just updated my answer in that post.

完全抱歉。你在这里提到的解决方案是我发布的,是不正确的。我刚刚在那篇文章中更新了我的答案。


Don't use the array initialization style that I originally posted:


不要使用我最初发布的数组初始化样式:

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = dataset; // this assigns the *same* object reference to every 
                       // member of the person array.

}


This is the correctway to initialize your person array:


这是初始化 person 数组的正确方法:

var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = {val1 : 0, val2 : 0, val3 : 0}; // do this to create a *unique* object 
                                              // for every person array element
}


If you use the correct array initializtion shown directly above, then you can increment val3 like this with each loop iteration:


如果您使用上面直接显示的正确数组初始化,那么您可以在每次循环迭代中像这样递增 val3:

var person = [];
var totalPeople = 10;

for(var i = 0; i < totalPeople; i++) {
  person[i] = {val1 : 0, val2 : 0, val3 : 0};
  person[i]['val3'] = i;
}


Sorry again for the bad information that I provided in the other post. (All other info is correct. Just the array initialization code was bad.) I hope this updated information helps.


再次为我在另一篇文章中提供的错误信息感到抱歉。(所有其他信息都是正确的。只是数组初始化代码不好。)我希望这些更新的信息有帮助。

回答by reyaner

This should be the right:

这应该是正确的:

person[1].val3 += 1;

回答by Santiago Nicolas Roca

This should work.

这应该有效。

var dataset = {val1 : 0, val2 : 0, val3 : 0};
var person = [];
var totalPeople = 10;

for(var i = 0; i <totalPeople; i++) {
   dataset[i].val3 ++; 
}

Could you explain more what you are trying to achieve?

你能解释更多你想要达到的目标吗?