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?
This should be the right:
person[1].val3 += 1;
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With