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

4 Answers 4

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]);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

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

4 Comments

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...
It works, but... it rhymes with "evil." stackoverflow.com/questions/86513/…
@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
var x = ['text1','text2','text3']; for (var i =0; i< x.length; i++) { console.log(x[i]); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.