JavaScript函数数组

var array_of_functions = [

    first_function('a string'),

    second_function('a string'),

    third_function('a string'),

    forth_function('a string')

]


array_of_functions[0];

这不能按预期工作,因为创建数组时将执行数组中的每个函数。


通过执行以下操作来执行数组中任何函数的正确方法是:


array_of_functions[0];  // or, array_of_functions[1] etc.

谢谢!


蝴蝶刀刀
浏览 546回答 3
3回答

动漫人物

var array_of_functions = [    first_function,    second_function,    third_function,    forth_function]然后要在数组中执行给定函数时:array_of_functions[0]('a string');

跃然一笑

我认为这就是原始海报要实现的目标:var array_of_functions = [&nbsp; &nbsp; function() { first_function('a string') },&nbsp; &nbsp; function() { second_function('a string') },&nbsp; &nbsp; function() { third_function('a string') },&nbsp; &nbsp; function() { fourth_function('a string') }]for (i = 0; i < array_of_functions.length; i++) {&nbsp; &nbsp; array_of_functions[i]();}希望这会帮助其他人(例如20分钟前:-)帮助我寻找有关如何在数组中调用JS函数的任何提示。

慕无忌1623718

如果没有您要完成的工作的更多细节,我们有点猜测。但是您也许可以摆脱使用对象表示法来做类似这样的事情...var myFuncs = {&nbsp; firstFunc: function(string) {&nbsp; &nbsp; // do something&nbsp; },&nbsp; secondFunc: function(string) {&nbsp; &nbsp; // do something&nbsp; },&nbsp; thirdFunc: function(string) {&nbsp; &nbsp; // do something&nbsp; }}并打电话给他们之一...myFuncs.firstFunc('a string')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript