我正在寻找一个关于这个的伎俩.我知道如何在Javascript中调用动态的任意函数,传递特定的参数,如下所示:
function mainfunc(func, par1, par2){
window[func](par1, par2);
}
function calledfunc(par1, par2){
// Do stuff here
}
mainfunc('calledfunc', 'hello', 'bye');
Run Code Online (Sandbox Code Playgroud)
我知道如何在mainfunc中使用arguments []集合传递可选的无限参数,但是,我无法想象如何向mainfunc发送任意数量的参数以动态发送到calledfunc ; 我怎么能完成这样的事情,但有任意数量的可选参数(不使用丑陋的if-else)?:
function mainfunc(func){
if(arguments.length == 3)
window[func](arguments[1], arguments[2]);
else if(arguments.length == 4)
window[func](arguments[1], arguments[2], arguments[3]);
else if(arguments.length == 5)
window[func](arguments[1], arguments[2], arguments[3], arguments[4]);
}
function calledfunc1(par1, par2){
// Do stuff here
}
function calledfunc2(par1, par2, par3){
// Do stuff here
}
mainfunc('calledfunc1', 'hello', 'bye');
mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');
Run Code Online (Sandbox Code Playgroud) 此代码将函数添加到数组:
var fArr = []
fArr.push(test())
fArr.push(test())
function test(){
console.log('here')
}
Run Code Online (Sandbox Code Playgroud)
但是,test()每次将函数添加到数组时都会调用该函数fArr
可以在不调用函数的情况下将函数test()添加到数组中fArr吗?
我试图fArr用函数填充数组,然后迭代fArr并调用函数,而不是调用函数,因为它们被添加到fArr当前行为.