有没有办法将值数组转换为函数参数而不必更改函数以接受单个数组?
我的情况是我需要动态加载我的网页部分(我使用jquery .load来执行此操作),当加载完成时,我需要调用带参数的函数。问题是回调函数有不同数量的参数,而我不必重写每个函数来接受单个参数对象。
function f(a, b){
// does stuff
}
function g(a, b, c){
// does other stuff
}
function Bootstrap(DivNameToLoad, Callbackname, CallbackArgs){
// Callbackname is a string name of the function to be called when load is complete
// CallbackArgs is a [] with the values to be passed to the callback function
$('#' + DivNameToLoad + 'PlaceholderDiv').load(DivNameToLoad + '.html', function(){
// Call the callback function
window[CallbackName](CallbackArgs); // This is where I have a problem
});
}
//Call the bootstrap function and callback f passing in the values 'alpha' and 'bravo' for a and b
Bootstrap('SomeDiv', 'f', ['alpha', 'bravo']);
//Call the bootstrap function and callback g passing in the values 'alpha', 'bravo' and 'charlie' for a, b and c
Bootstrap('SomeDiv', 'f', ['alpha', 'bravo', 'charlie']);
如果这是不可能的话,我不会感到惊讶,但也许有人知道一个聪明的方法吗?