1

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?

1
  • 4
    Why not use an associative array instead? Commented Nov 20, 2012 at 15:19

2 Answers 2

6

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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';

3 Comments

Instead of arr[arr.length] use arr.push().
True that, I thought I read somewhere arr[arr.length] is faster but it seems it's not. Edited.
It wasn't concerned with speed, I just figured a.push is less confusing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.