Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  95] [ 6]  / answers: 1 / hits: 22927  / 10 Years ago, tue, september 16, 2014, 12:00:00

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?


More From » variables

 Answers
64

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.


[#69436] Saturday, September 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ammonderekm

Total Points: 247
Total Questions: 105
Total Answers: 98

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;