FongYu
FongYu

Reputation: 767

How to dynamically create variable name?

I need to create javascript objects that base on user defined number. So if user defines 20, then I need to create 20 variables.

var interval_1=0, interval_2=0, interval_3=0, interval_4=0, interval_5=0... interval_20=0;

how do I do it so the name of the object can be dynamically created?

for (i=0; i<=interval; i++){
    var interval_ + i.toString() = i;
}

Upvotes: 1

Views: 4639

Answers (4)

YS.
YS.

Reputation: 1828

for (i=0; i<=20; i++){
    window["interval_" + i.toString()] = i;
}

Upvotes: 3

Will Klein
Will Klein

Reputation: 2294

Use an array:

var i, count, interval = [];

// user defines count, 20 for example
count = 20;

for (i = 0; i < count; i++) {
    interval.push(i);
}

// interval[0] === 0
// interval[19] === 19
// interval.length === 20

Note, this starts the index at 0 and goes up to count - 1. Do not use i <= count unless you start i at 1.

Here is a jsFiddle to illustrate. Hit F12 to open dev tools in most browsers and look at console, or change console.log() to alert().

Link: http://jsfiddle.net/willslab/CapBN/1/

Alternatively, you could setup a single object with properties for each value:

var i, count, intervals = {};

count = 20;

for (i = 0; i < count; i++) {
    intervals["interval_" + i] = i;
}

//intervals.interval_0 === 0
//intervals.interval_19 === 19)

Link: http://jsfiddle.net/willslab/EBjx7/2/

Upvotes: 3

RobG
RobG

Reputation: 147363

Javascript variables can be created by:

  1. a variable declaration, e.g. var x;
  2. assigning a value to an undeclared variable, e.g. y = 'foo';
  3. an identifier in a formal parameter list, e.g. function bar(x, y, z);
  4. using eval, e.g. eval( 'var x = 4');

If all else fails and you want say 5 variables, you can do:

var s = [];
var i = 5;
while (i--) {
  s[i] = 'a' + i;
}

eval('var ' + s.join(',') + ';');

alert(a0); // shows undefined

If a0 wasn't defined, the last step would throw a reference error.

Of course the issue you now have is how to access them. If they are created as global variables, you can use:

globalObj['a' + i];

where globalObj is usually window, however there is no equivalent for accessing function variables since you can't access their variable object.

So the usual solution is to put things into arrays or objects where you can iterate over the properties to find things you don't know the name of.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Erm, use an array?

for( i=0; i<=count; i++) array[i] = i;

Upvotes: 4

Related Questions