user3422998
user3422998

Reputation: 105

Dynamic variable in loop javascript

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.

Upvotes: 1

Views: 4363

Answers (3)

Tom&#225;š Zato
Tom&#225;š Zato

Reputation: 53129

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

Upvotes: 1

punund
punund

Reputation: 4421

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).

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227200

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.

Upvotes: 4

Related Questions