user375566
user375566

Reputation:

Javascript object variable name as number

Below, i shows up as "i", not the number I am iterating through. How do I correct this? Thanks!

for (i = 0; i < 10000; i++) {
     var postParams = {
        i : 'avalueofsorts'
     };
}

Upvotes: 3

Views: 488

Answers (2)

generalhenry
generalhenry

Reputation: 17319

To expand on the 'you want an array comment':

for (var i = 0, postParams = []; i < 10000; i++) {
     postParams.push('avalueofsorts');
}

In javascript arrays are just objects with a few extra methods (push, pop etc...) and a length property.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186662

for (var i = 0, l = 10000; i < l; ++i) {
     var postParams = {};
     postParams[i] = 'avalueofsorts'
}

Per Cybernate's comment, you can create the object beforehand and just populate it otherwise you create it each time. You probably want this:

for (var i = 0, l = 10000, postParams = {}; i < l; ++i) {
     postParams[i] = 'avalueofsorts'
}

Upvotes: 7

Related Questions