sergserg
sergserg

Reputation: 22264

Creating a javascript variable using another variable as a counter

Say I want something like this:

var i = 0;

for (i upto 100) {
    var x+i = "This is another variable altogether";
    i++;
}

The javascript interpreter would see:

var x = "This is another variable altogether";
var x1 = "This is another variable altogether";
var x2= "This is another variable altogether";
var x3 = "This is another variable altogether";
var x4 = "This is another variable altogether";

Can I use a variable counter to increment the name of the variable so I have distinct variables altogether?

Upvotes: 1

Views: 155

Answers (2)

Doug
Doug

Reputation: 3312

Technically, yes.

If you're operating in the global scope which I suspect you are, you can do this:

for (var i=0; i<100; i++){
  window["x"+i]="This is another variable altogether";
}

console.log(x1);

You should however be doing this kind of thing with an array, so:

var arr=[];
for (var i=0; i<100; i++){
  arr[i]="This is another variable altogether";
}

console.log(arr[1]);

Upvotes: 6

Michał Miszczyszyn
Michał Miszczyszyn

Reputation: 12711

You should not use distinct variables for that. Give a try to Array:

var arr = [];
...
arr.push('my var');

or object:

var ob = {};
...
ob[counter] = 'my var';

Upvotes: 1

Related Questions