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)?
}
5
  • 1
    eval(). Haters gonna hate Commented Sep 26, 2013 at 13:57
  • 4
    Use an array instead Commented Sep 26, 2013 at 13:58
  • 2
    If it's global alert(window[var_name]). Commented Sep 26, 2013 at 13:58
  • 2
    @Johan: evalers gonna eval. Commented Sep 26, 2013 at 13:59
  • 1
    @RocketHazmat No, they're gonna evaluate ;) Commented Sep 26, 2013 at 14:03

5 Answers 5

3

DEMO

for (var i = 0; i < 5; i++) {
    var var_name = 'msg_' + i;
    window[var_name] = i;
    console.log(window[var_name]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You mean window[var_name] :-)
2

You should put the values inside an array.

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

for (var i = 0; i < n; i++)
{
    alert (messages[i])
}

Comments

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

Comments

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]);
}

1 Comment

if you don't understand how it works don't click -1
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.