繁体   English   中英

通过键JavaScript从关联数组调用函数

[英]Call a function from associative array by key JavaScript

在JavaScript中,我具有类似的函数关联数组(例如类的静态字段):

functions={'name': function(){},'name':function(){}};

每个函数都对数组进行处理。 我也有方法:

this.doSomethind= function(name, array){//class member

我需要调用通过名称查找它的函数之一。

$.each(functions, function(key, value) {
                 if(key == name)
                    //here I need to call function with array as paremeter. It seems value(array); doesn't work.
                        }); 
}

抱歉,这是一个愚蠢的问题,我刚接触JavaScript。 谢谢

如果我正确理解了您的问题,您应该可以说:

functions[name](array);

而不是$.each()循环。

尝试这个:

value.apply(this, [array])

就您所提供的信息而言,您无法从类方法中访问范围之外的参数。 在您的示例中,拼写已更正

  //'array' is undefined / out of scope
  this.doSomething = function(name,array){
    //array is defined / in scope!
   };

否则,如果您正在谈论的变量数组在某个范围的某个范围内定义,则第一个答案将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM