[英]Call a function from associative array by key JavaScript
In JavaScript I have associative array of functions like this (like static field of a class): 在JavaScript中,我具有类似的函数关联数组(例如类的静态字段):
functions={'name': function(){},'name':function(){}};
each function do something with array. 每个函数都对数组进行处理。 I also have method:
我也有方法:
this.doSomethind= function(name, array){//class member
I need to call one of the functions finding it by name. 我需要调用通过名称查找它的函数之一。
$.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.
});
}
Sorry if it's a dumb question, I'm just new in JavaScript. 抱歉,这是一个愚蠢的问题,我刚接触JavaScript。 Thanks
谢谢
If I'm understanding your problem correctly, you should just be able to say: 如果我正确理解了您的问题,您应该可以说:
functions[name](array);
Instead of the $.each()
loop. 而不是
$.each()
循环。
尝试这个:
value.apply(this, [array])
As far as the information you have provided, you cannot access a parameter that is not yet in scope from the class methods. 就您所提供的信息而言,您无法从类方法中访问范围之外的参数。 in your example spelling corrected
在您的示例中,拼写已更正
//'array' is undefined / out of scope
this.doSomething = function(name,array){
//array is defined / in scope!
};
Otherwise if the variable array you are talking about is defined in the scope somewhere, the first answer will work. 否则,如果您正在谈论的变量数组在某个范围的某个范围内定义,则第一个答案将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.