0

I suspect I am making a mistake in a basic JavaScript syntax.

var my_array = new Array(10);

for (var count=0; count<my_array.length; count++) {
var my_array+count = "This is a variable number "+count+".";
document.write(my_array+count);
}

I want the loop to create series of variables that should be called my_array0, my_array1, my_array2, and so on. The code above is how I tried to do that, but it doesn't work. What's the correct way of naming the variable inside the loop?

EDIT: I know I could use my_array[count], but that's not what I'm looking for. What I need is to be able to name a variable inside the loop, using the index as part of the name of the variable.

Dimitri Vorontzov
  • 7,834
  • 12
  • 48
  • 76
  • You need to do `my_array[count]` instead of `var my_array+count` – karthikr May 30 '13 at 14:39
  • 1
    Why do you want a series of variables with those names? What are you trying to accomplish here? If you want ten arrays, create ten arrays and put them in another array. Do you know what an array is? It is a thing that holds a list of multiple other things. – 15ee8f99-57ff-4f92-890c-b56153 May 30 '13 at 14:41
  • No, @Ed, what I want is series of variables that all have different names. I will be using array[count] for a different purpose within a loop, so I need to separate the variables from the array. – Dimitri Vorontzov May 30 '13 at 14:44
  • 1
    What are you trying to DO? WHY do you want a series of variables with different names? If you want ten things, put them in an array. If you want to put something else in a different array, create a second array. – 15ee8f99-57ff-4f92-890c-b56153 May 30 '13 at 14:44
  • I want to do something like this: var my_array0 = new Image(); my_array0.src = my_array[0]; – Dimitri Vorontzov May 30 '13 at 14:45
  • But in more general terms, @Ed, I want to be able to dynamically name a variable inside a loop, using the value of the count as part of variable name. Is that possible at all? – Dimitri Vorontzov May 30 '13 at 14:48
  • 1
    An image isn't an array. Why are you putting an image in a variable named "my_array0"? You want two arrays: var imagesrc = new Array(10); var images = new Array(10); Populate imagesrc[0] through imagesrc[9] with the urls, then populate images with the Images, then assign the .src properties. – 15ee8f99-57ff-4f92-890c-b56153 May 30 '13 at 14:49
  • Probably a good way to do that, @Ed, but my question remains: how do I use the count variable as part of the name of a different variable inside a loop? – Dimitri Vorontzov May 30 '13 at 14:51
  • 1
    Don't do that. That's what arrays are for. They are much easier to use. It's cool to try to think of your own new ways to solve problems, but this one isn't a great idea. It's hard enough to learn programming without trying to do things the language doesn't want you to do. – 15ee8f99-57ff-4f92-890c-b56153 May 30 '13 at 14:51
  • @Figaro check my answer mate, but Ed has a point. – Sharky May 30 '13 at 14:51
  • anybody cares to explain why my answer http://stackoverflow.com/questions/16839033/variable-name-within-a-loop/16839168#16839168 is downvoted???? – Sharky May 30 '13 at 15:07
  • possible duplicate of [Javascript "Variable Variables": how to assign variable based on another variable?](http://stackoverflow.com/questions/592862/javascript-variable-variables-how-to-assign-variable-based-on-another-variabl) and [lots of others](https://www.google.co.uk/search?q=site%3Astackoverflow.com+javascript+variable+variables&oq=site%3Astackoverflow.com+javascript+variable+variables&aqs=chrome.0.57j58j61.5718j0&sourceid=chrome&ie=UTF-8). – Quentin May 30 '13 at 15:09
  • 1
    I experimented with various possible solutions, and your suggestion of using two arrays, @Ed, is the best one. I had to accept the answer that most directly addresses my original question, but you made me rethink the way I approached the problem, and I very much appreciate it. Your suggestion was the solution. – Dimitri Vorontzov May 30 '13 at 15:21

8 Answers8

5

If you want to set the elements of an array, use the [] syntax:

var my_array = new Array(10);

for (var count=0; count<my_array.length; count++) {
  my_array[count] = "This is a variable number "+count+".";
  document.write( my_array[count] );
}

Furthermore, when specifying just an element of an array and not the array itself, drop the var in front of it!

Sirko
  • 72,589
  • 19
  • 149
  • 183
  • That would be the obvious solution, but that's not what I want, for a number of reasons. I actually want to include the number in the name of the variablem rather than use my_array[count]. – Dimitri Vorontzov May 30 '13 at 14:40
  • 1
    @Figaro If you want to create variables with "dynamic names" you need some pointer to the scope, where you want to add them. If this is the global scope, e.g., you could replace `my_array` with `window` inside the `for` loop, to create global variables of the respective name. – Sirko May 30 '13 at 14:42
  • Sounds like a step in the right direction, @Sirko. That's exactly what I want to do, the variables with "dynamic names", but I think I want them local in scope – how can I do that? – Dimitri Vorontzov May 30 '13 at 14:49
  • @Figaro a starting point might be the answers in [this question](http://stackoverflow.com/q/2051678/1169798), but I know of no equivalent of the `window` object for a function scope. You could maybe bind your variables to `this`. – Sirko May 30 '13 at 14:53
  • Tried window[count], @Sirko, it does what I want it to do, but it slows down loading of the page considerably. How would you bind variables to `this` - `this[count]`, or in some other fashion? – Dimitri Vorontzov May 30 '13 at 15:01
  • @Figaro Like mentioned many times in the comments, this is no good approach in general. Just use an object or array and put all your variables in there. But yes, `this[count`] should work, but maybe has some side effects, you don't want (see object orientation in JS for what `this[x]` is usually used). – Sirko May 30 '13 at 15:17
2

What's the correct way of naming the variable inside the loop? You don't.

If you just want a variable to hold that particular value, just use an ordinary variable. If you want lots of different values, stick it inside an array or object. But that's redundant here since you already have an array, so I'm really not sure what you're trying to achieve.

Antimony
  • 37,781
  • 10
  • 100
  • 107
2

This pattern is questionable, and the array seems unnecessary; however, here is one way to do it:

var my_array = new Array(10);

for (var count = 0; count < my_array.length; count++) {
  window['my_array' + count] = "This is a variable number " + count + ".";
  document.write(window['my_array' + count]);
}
Noah Freitas
  • 17,240
  • 10
  • 50
  • 67
1

And if none of the previous answers suits you, you can always use eval()

var varName = 'my_array'
for (var count=0; count<my_array.length; count++) {
  eval(varName+count +" = This is a variable number "+count+".");
}

Edit: @Noah Freitas provides a better answer, without using eval().

ignasi
  • 443
  • 4
  • 8
0

You should use an array.

var myarray = new Array();
myarray[0] = "1";
myarray[1] = "2";
myarray[2] = "3";
Nimajen
  • 81
  • 7
0

You're redefining my_array inside the loop, and not accessing the variable correctly either. Try:

var my_array = new Array(10);

for (var count=0; count<my_array.length; count++) {
    my_array[count] = "This is a variable number "+count+".";
    console.log(my_array[count]);
}

JS Fiddle

dKen
  • 3,078
  • 1
  • 28
  • 37
0

You can't execute on the left-hand side of the assignment operator (=), you can only assign. Execution, in javascript, takes place on the right hand side.

var my_array = new Array(10);
var var_hashmap = {}; // create a new object to hold our variables.

for (var count = 0; count < my_array.length; count++) {
    var key = "my_array" + count;
    var value = "This is a variable number " + count + ".";
    var_hashmap[key] = value;
    document.write(var_hashmap[key]);
};
Mark Feltner
  • 2,041
  • 1
  • 12
  • 23
0
var my_array = new Array(10);

for (var count=0; count<my_array.length; count++)
{
    eval("var my_array" + count + " = 'This is a variable number'+count+' and the variable name is my_array'+count");

}

alert(my_array0);
alert(my_array1);
alert(my_array2);
alert(my_array3);
alert(my_array4);
alert(my_array5);
alert(my_array6);
alert(my_array7);
alert(my_array8);
alert(my_array9);

http://jsfiddle.net/pe97W/4/

Sharky
  • 6,154
  • 3
  • 39
  • 72
  • downvote? for what? OP says "EDIT: I know I could use my_array[count], but that's not what I'm looking for. What I need is to be able to name a variable inside the loop, using the index as part of the name of the variable." also says "but my question remains: how do I use the count variable as part of the name of a different variable inside a loop?" --i answered his question, first. And that's downvoting? – Sharky May 30 '13 at 14:54