Can I store JavaScript functions in arrays?

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

提交回复
热议问题