Can I store JavaScript functions in arrays?

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

    The answer is has a simple answer, but it doesn't to be simplified by the answers in this thread. The simple answer is yes you can place function in an array. In fact, can declare variables and reference them in your function.

    Example:

    let a = 1;
    let b = 2;
    
    let arr = [
      a,
      b,
      function () {
        return a + b;
       },
      ];
    
    console.log(arr[2]()); // return 3
    console.log(typeof arr); // returns object

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

    The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that.

    Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with.

    var functions = {
        blah: function() { alert("blah"); },
        foo: function() { console.log("foo"); }
    };
    

    call as

    functions.blah();
    

    or

    functions["blah"]();
    
    0 讨论(0)
  • 2021-01-30 06:16

    Here is an array that contains various data types, including a function.

    Although there is an object in this example, the function is not within the object.

    If you replace this object with a string, the function will still work as planned.

    I can call the function from within or without the array.

    myArray = [
            1,
            true,
            "String",
            {
                name: "trey",
                age: 43,
            },
            [1,2,3,4],
            myFunction = function(){
                console.log("What\'s up!");
            },
            myArray[5](),
        ];
        console.log(myArray);
        myArray[5]();
    

    Here is the output:

    What's up!
    [ 1, true, 'String', { name: 'trey', age: 43 }, [ 1, 2, 3, 4 ], [Function], undefined ]
    What's up!
    
    0 讨论(0)
提交回复
热议问题