0

In javascript, the way to declare a var is: var msg = 'hello', and it is simply to call msg will get the value of 'hello' if I am now have a number of var, e.g. msg_1, msg_2 ... msg_n would there be a way to get the value by calling something like

for (var i = 0; i < n; i++)
{
 var var_name = 'msg_' + i;
 alert (var_name)?
}
user2625363
  • 845
  • 2
  • 10
  • 15

5 Answers5

3

DEMO

for (var i = 0; i < 5; i++) {
    var var_name = 'msg_' + i;
    window[var_name] = i;
    console.log(window[var_name]);
}
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
2

You should put the values inside an array.

var messages = ["first", "second", "third"];

for (var i = 0; i < n; i++)
{
    alert (messages[i])
}
Itay
  • 16,601
  • 2
  • 51
  • 72
2

I would suggest use to use array instead of what you are doing.

var myVarialbes= [];
for (var i = 0; i < n; ++i) {
    myVarialbes[i] = "some stuff" + i;
}
Sachin
  • 40,216
  • 7
  • 90
  • 102
0

Here you got a simple method:

var var_name=''; //declare variable only once
for (var i = 0; i < 5; i++) //You should change 5 to n
{
 var_name = 'msg_' + i;
 alert (var_name.split('_')[1]);
}
PingOfDeath
  • 137
  • 5
0
function do_test(){
    var v1 = "variable 1";
    var v2 = "variable 2";
    var v3 = "variable 3";
    for (i=1;i<4;i++){
        var o = eval("v"+i); // you actually need this
        alert (o);
    }
}

But why don't you use arrays?

btlr.com
  • 139
  • 5