Can I store JavaScript functions in arrays?

前端 未结 9 1880
时光说笑
时光说笑 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 05:55

    You want an object literal, not an array.

    x = { 'dothis': function() { alert('hi'); } };
    

    Object

    x['dothis']()
    

    You can also dynamically invoke

    y = 'dothis';
    x[y]()
    

    Static/hard coded invocation:

    x.dothis()
    

    If you do want an array though:

    x = [function(){alert('hi');}][0]()
    
    0 讨论(0)
  • 2021-01-30 05:55

    Basically, a function is a special type of object in JavaScript. And in JavaScript, in array you can store anything (not necessarily of the same type). So going by this, yes!, you can store a function, object, and primitive values in an array in JavaScript:

    var arr = ["Hello", true, false, 1, {name: "Arshad"}, function(){}]
    

    And you can mix the object and function to make the named function like:

    { callBythisname: function(){ .... }}
    

    You can store this object in an array as well:

    var arr = [{ callBythisname: function(){ .... }}];
    

    If you want to call it, call like:

    arr[0].callBythisname();
    
    0 讨论(0)
  • 2021-01-30 05:58

    You even can use a function as the name of the property:

    var func = function(a, b){alert(a+b)};
    var obj = {};
    obj[func] = 2;
    
    0 讨论(0)
  • 2021-01-30 06:03

    You can actually do that. Just declare it outside the array, like so...

    const your_function = function(){ console.log("I am your function") }
    
    const group = [0, "lizard", false, your_function()]
    
    group[3]
    

    You may also change where it's called, if you want to...

    const your_function = function(){ console.log("I am your function") }
    
    const group = [0, "lizard", false, your_function]
    
    group[3]()
    

    Functions were named wrong :/ sry

    0 讨论(0)
  • 2021-01-30 06:05

    You can store things directly in an array, but as an object, for example:

    var Functions = { DoThis: function() { alert("do this"); } };
    
    Functions['DoThis'](); //alerts "do this"
    Functions.DoThis()     //alerts "do this"
    

    You can give it a try here.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题