Access Javascript variables dynamically

后端 未结 4 1575
刺人心
刺人心 2020-11-28 16:07

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         


        
4条回答
  •  天涯浪人
    2020-11-28 16:42

    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.

提交回复
热议问题