【问题标题】:How can I pass parameters from an array as distinct arguments to a javascript function? [duplicate]如何将数组中的参数作为不同的参数传递给 javascript 函数? [复制]
【发布时间】: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


【解决方案1】:

使用Function.apply()方法

window[CallbackName].apply(null, CallbackArgs);

【讨论】:

  • 这正是我所需要的。谢谢!
猜你喜欢
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
  • 2013-01-27
  • 2015-11-08
相关资源
最近更新 更多