5

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 for loop.

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?

Community
  • 1
  • 1
Swift
  • 61
  • 1
  • 4
  • 8

3 Answers3

7

This should be the right:

person[1].val3 += 1;
reyaner
  • 2,799
  • 1
  • 12
  • 17
2

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?

1

Totally sorry. The solution that you're referring to here was 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 correct way to initialize your 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
}


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

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.

Community
  • 1
  • 1
Gerald LeRoy
  • 1,227
  • 2
  • 11
  • 17