Can I store JavaScript functions in arrays?

前端 未结 9 1886
时光说笑
时光说笑 2021-01-30 05:34

How can I store functions in an array with named properties, so I can call like

FunctionArray["DoThis"]

or even

Function         


        
9条回答
  •  再見小時候
    2021-01-30 06:06

    You can access an object's properties through its name (x["A"]). If you want to assign indexes (0 = "A") you have to do this, and here is an example. (I'm not sure if the for loop will work on any browser; I've tested on Firefox, but you can get the idea.)

    var x = {};
    
    x.A = function() { alert("func 1"); };
    x.B = function() { alert("func 2"); };
    
    
    var i = 0;
    for (a in x)
    {
        x[i] = x[a];
        ++i;
    }
    
    
    x[0](); // func 1
    x[1](); // func 2
    x["A"](); // func 1
    x["B"](); // func 2
    

提交回复
热议问题