Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variables programmatically?

Tags:

javascript

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.

like image 335
Derek 朕會功夫 Avatar asked Nov 29 '22 02:11

Derek 朕會功夫


2 Answers

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?

like image 150
Matt Ball Avatar answered Nov 30 '22 23:11

Matt Ball


I guess its better for you to go with an array, like:

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

Or if you really want the long list of variables, try this. But its using eval()

function l(){
    var js = '';
    for(var i=0; i<20; i++){
        js += 'var a'+i+' = '+2*i+';'
    }
    eval (js);
}
like image 44
Akhil Sekharan Avatar answered Dec 01 '22 00:12

Akhil Sekharan