1

I want to create a dynamic variable in the loop. I found something about eval and window but I don't know how to use this.

This is my loop and i want to create a 9 variables names from m1 to m9. I mean that the name of variable must be m1 to m9

for(i=1; i<10; i++){

  var m+i = "Something"

}

Please help me with this. Really appreciate.

user3422998
  • 105
  • 1
  • 7

3 Answers3

4

You don't want to create 9 variables. Trust me. You want to create an object.

var m = {};
for(var i=1; i<10; i++){
    m[i] = "Something";
}

You can also create an array (m = []), but since you are starting at 1 and not 0, I'd suggest an object.

Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • I would go for the array as it has numbered indices ! – adeneo May 22 '14 at 13:54
  • 1
    If the OP doesn't need to start at 1 (for some reason) then, I'd agree @adeneo, but Rocket's solution already states the reasoning for using an object is tied to the OP's code stating it starts at 1. Of course, it'd also be easier to advise the OP if they could explain /why/ they felt the need to have dynamic ordered variables in the first place. – Jason M. Batchelor May 22 '14 at 13:56
  • @adeneo: I originally had the answer with an array, but I changed to an object, because in this case `m[0]` would be unset, and I was unsure if that would be a problem here. What if his `i` started at `10` or `100`? That is why I used an object. – gen_Eric May 22 '14 at 13:59
  • @MattiasBuelens: Thanks for editing the post. I copied and pasted the OP's code, so I forgot to fix the `var` :-) – gen_Eric May 22 '14 at 14:00
2

But if you still want to create 9 variables, despite all that, you still can:

for(i=1; i<10; i++){
  eval('var m'+i+'='+i)
}

(And yes, you shouldn't).

punund
  • 4,321
  • 3
  • 34
  • 45
1
var object = {};     
var name = "m";
for(i=1; i<10; i++){
  object[name+i] = "Something";
}
console.log(object.m1); // "Something", same for m2,m3,m4,m5...,m9

However consider if the "m" is really necessary, arrays are way faster:

var array = [];
for(i=1; i<10; i++){
  array.push("Something");
}
console.log(array[0]); // "Something", same for 1,2,...,8
punund
  • 4,321
  • 3
  • 34
  • 45
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778