Can I store JavaScript functions in arrays?

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

提交回复
热议问题