Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

javascript - Declare variables programmatically?

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...