How to increase the value inside an object variable

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 am trying to do one of the auto increment values ​​inside another loop for.

I 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?

+4
source share
3 answers

Sorry completely. The solution you have in mind here was published by me and is incorrect. I just updated my answer in this post.


Do not 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 correct way to initialize the person array:

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
}


, , 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;
}


, . ( . .) , .

0

:

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

That 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 about what you are trying to achieve?

+1
source

All Articles