【发布时间】:2015-04-03 21:48:47
【问题描述】:
有没有一种方法可以将一组值转换为函数参数,而无需将函数更改为接受单个数组?
我的情况是我需要动态加载网页的某些部分(我正在使用 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']);
如果这不可能,我不会感到惊讶,但也许有人知道一个聪明的方法来做到这一点?
【问题讨论】:
-
是的,这是重复的。抱歉,@Barmar。
标签: javascript arrays arguments