Can I store JavaScript functions in arrays?

前端 未结 9 2022
时光说笑
时光说笑 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

    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();
    

提交回复
热议问题