Declare variables programmatically?

前端 未结 3 914
醉梦人生
醉梦人生 2020-12-11 23:59

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

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


        
相关标签:
3条回答
  • 2020-12-12 00:04

    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);
    }
    
    0 讨论(0)
  • 2020-12-12 00:23

    As a matter of fact, I think using a object is a good idea.

    var scope = {}
    for (var i=1;i<=20;i++) {
      scope['a'+i] = 'stuff';   
    }
    

    The result will be you have a scope object that contain every newly create variable you want!

    0 讨论(0)
  • 2020-12-12 00:25

    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?

    0 讨论(0)
提交回复
热议问题