1

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

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
comebal
  • 946
  • 3
  • 14
  • 30

4 Answers4

6

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]);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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.

Moin Zaman
  • 25,281
  • 6
  • 70
  • 74
1

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]);   
    }
hsuk
  • 6,770
  • 13
  • 50
  • 80
0

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

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
  • I have a question: Are you crazy? This is probably the worst use of `eval` I have ever seen, and I've seen some pretty bad stuff... – Niet the Dark Absol Jul 17 '12 at 04:17
  • 1
    It works, but... it rhymes with "evil." http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – approxiblue Jul 17 '12 at 04:18
  • @Kolink thank you for your feedback. This is a silly, simple problem to begin with. I upvoted your answer its a more fundamentally stable approach. I am not crazy – Glenn Ferrie Jul 17 '12 at 04:19
  • var x = ['text1','text2','text3']; for (var i =0; i< x.length; i++) { console.log(x[i]); } – Abhishek Mehta Jul 17 '12 at 04:20