简体   繁体   中英

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):

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. Thanks

If I'm understanding your problem correctly, you should just be able to say:

functions[name](array);

Instead of the $.each() loop.

尝试这个:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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