简体   繁体   中英

can i search an array of functions and run the searched function?

I am trying to write an application that searches an array of functions and does the function that was found.

var search = 'test';
var valid_input_array = [
     function test(){console.log('test');},
     function abc(){console.log('abc');}
];

for (i = 0; i < valid_input_array.length; i++) {

  if (valid_input_array[i].name === search) {
    valid_input_array.search;
  }

}

It does find the function but it doesn't run it.

You need to call found function

 var search = 'test'; var valid_input_array = [function test(){console.log('test');},function abc(){console.log('abc');}]; for(i = 0; i < valid_input_array.length; i++){ if(valid_input_array[i].name === search){ valid_input_array[i]() } } 

You could also use Array#find()

 var search = 'test'; var valid_input_array = [ function test(){console.log('test');}, function abc(){console.log('abc');} ]; var funcWanted = valid_input_array.find(function(fn) { return fn.name === search }) // only call it if find doesn't return false funcWanted && funcWanted() 

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