Access Javascript variables dynamically

I know you might think this is a duplicate or a dumb question. But the answers doesn't help me.

Here's my simple problem:

var option1 = "some text";
var option2 = "some text";
var option3 = "some text";

I want to access the elements "option1, option2, option3" in a for loop:

for(var i = 1; i < 4; i++)
{
    alert(option+i);   
}

I know that it shouldn't be option+i but I dont know how to solve this.

Thanks for the help in advance.

If you find this to be a duplicate just mark this question. Thanks

Answers:

Answer

Please try this one:

    option = new Array();
    option[1] = "some text";
    option[2] = "some text";
    option[3] = "some text";
    for(var i = 1; i < 4; i++)
    {
        alert(option[i]);   
    }
Answer

If they are variables in the window scope, then you can access window['option'+i]. However, you really should just use an array:

var option = [
    "some text",
    "option 2",
    "option 3"
];
for( var i=0; i<3; i++) alert(option[i]);
Answer

change your loop to look like this:

for(var i = 1; i < 4; i++)
{
    alert(eval("option"+i));   
}

Let me know if you have any questions

Answer

Try this:

var option1 = "some text";
var option2 = "some text";
var option3 = "some text";

for(var i = 1; i < 4; i++)
{
 alert(eval('option'+i) + '\n');
}

It's better if you try and use an array or access it via window as Kolink posted. And if you do use eval, make sure nothing that is not in your control gets eval'ed as its a security risk.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.