Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create a bunch of variables like this:

function l(){
    var a1 = 2,
        a2 = 4,
        a3 = 6,
        a4 = 8,
          .
          .
        a20 = 40;
}

But this is taking too many lines, and I am searching for a way to do it smarter. This is what I have come up:

function l(){
    for(var i=0; i<20; i++){
        var ("a"+i) = 2*i;
    }
}

But it probably won't work, and if it works (it does not) the variables will still be inside the for scope. Any ideas?

window["a"+i] or eval(...)

These don't work because I don't want them to be in the global scope.

Usually an Array would be fine, but I am just experimenting if this is possible in JavaScript. Maybe in the future I would encounter something like this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

Don't do this. Do. Not. Do. This. Use an array.


Given the trouble you're having creating them programmatically, how do you think you'd refer to them programmatically?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...