【问题标题】:Firing named functions from an array with JavaScript?使用 JavaScript 从数组中触发命名函数?
【发布时间】:2011-04-18 09:10:02
【问题描述】:

我对 JavaScript 很陌生,但这个话题似乎只吸引了很少的论坛关注。给定一些简单的函数:

function do_something(){...};
function do_somemore(){...};
function do_something_else(){...};

我希望能够将这些显式分配给(此处为二维)数组中的单元格。

myMatrix[5][3] = do_something();
myMatrix[5][4] = do_somemore();
myMatrix[5][5] = do_something_else();

我想使用这种方法的原因是:

  1. 易于理解和维护。
  2. 消除了数组中潜在的冗余匿名函数分配。
  3. 任何给定的函数都可以分配给多个数组单元,例如:

    myMatrix[2][6] = do_somemore();
    myMatrix[5][4] = do_somemore();
    myMatrix[6][3] = do_somemore();
    

不幸的是,以下调用(基于各种论坛示例,加上一点“吸一听”)都失败了。

x = myMatrix[5][4]do_somemore();         -> "missing ; before statement"
x = (myMatrix[5][4])do_somemore();       -> "missing ; before statement"
x = (myMatrix[5][4]do_somemore)();       -> "missing ) in parenthetical"
x = (myMatrix[5][4])(do_somemore());     -> "is not a function"
x = (myMatrix[5][4])()do_somemore();     -> "missing ; before statement"
x = myMatrix[5][4]()do_somemore();       -> "missing ; before statement"
x = myMatrix[5][4]();                    -> "is not a function"
x = (myMatrix[5][4])();                  -> "is not a function"

由于我对 JavaScript 内部结构一无所知,因此我很乐意提供有关如何获取函数调用的建议触发

【问题讨论】:

  • 非常感谢所有贡献见解的人。代码在几分钟内正常工作,分配如下: myMatrix[5][4] = do_somemore; ..然后使用 myMatrix[left][right](); 调用前者我已经尝试过,但后者逃脱了我:-)
  • 如果没有一个答案能满足您的问题,请考虑选择一个答案或添加更具体的信息。

标签: javascript arrays function


【解决方案1】:

你应该这样分配它们:

myMatrix[5][3] = do_something;

【讨论】:

  • 确实如此。目前,OP 正在调用函数并将返回的值分配给矩阵。
  • 调用此类函数的正确语法是x = myMatrix[5][3]();。另请注意,这些括号称为“函数调用运算符”。
【解决方案2】:
myMatrix[5][3] = do_something;

您的方式会将值设置为函数的 RESULT!

【讨论】:

    【解决方案3】:

    我不完全清楚你在追求什么,但是:

    首先,在为数组赋值之前,该数组必须存在:

    var myMatrix = [];
    myMatrix[5] = [];
    myMatrix[5][3] = … // Then you can assign something
    

    那么,如果你想给一个函数赋值返回值

    myMatrix[5][3] = do_something();
    

    或者,如果您想分配函数本身

    myMatrix[5][3] = do_something;
    

    ……然后调用它并将其返回值赋给x

    var x = myMatrix[5][3](); 
    

    ... 与var x = do_something() 相同,只是函数内部this 将是myMatrix[5] 而不是window

    【讨论】:

      【解决方案4】:
      myMatrix[5][3] = do_something; 
      myMatrix[5][4] = do_somemore; 
      myMatrix[5][5] = do_something_else; 
      
      
      var x = myMatrix[5][3]();
      var y = myMatrix[5][4]();
      var z = myMatrix[5][5]();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-05
        相关资源
        最近更新 更多