为需要 N 个参数的函数传递参数数组

Passing array of arguments for a function which expects N number of arguments

基本上我想做的与此类似;

function methodX(arg1, arg2, ...) {}
methodX([arg1, arg2, arg3]);

在实际情况下,我有一个数组 (cbInfo),我正尝试将它与 jQuery.when() 一起使用,如下所示,但它似乎不起作用。那么有没有办法为需要 N 个参数的函数传递参数数组?

var cbInfo = [
    {
        templatePath: 'templates/level.html',
        callback: renderLevels
    },
    {
        templatePath: 'templates/alert.html',
        callback: renderAlerts
    }
];

function loadTemplates(cbInfo, cb) {
    var ajaxes = [],
        callbacks = [];

    cbInfo.forEach(function (elem) {
        ajaxes.push($.ajax({type: "GET", url: elem.templatePath}));
        callbacks.push(elem.callback)
    });

    $.when(ajaxes).then(
        function () {
            var args = Array.prototype.slice.call(arguments);
            callbacks.forEach(function (elem, index) {
                elem(args[index]);
            });
            cb();
        },
        function () {
            // failure
            console.error("loadTemplates() : could not load UI templates.")
        }
    );
}

更新: apply 和 spread 运算符都适用于其他情况。但是我正在尝试针对这种特定情况解决这个问题。我尝试使用 $.when().apply(null, ajaxes),但随后它抛出 Uncaught TypeError: $.when(...).apply is not a function 如何克服这个问题?而且我还要支持ES5

您可以为此使用函数 apply

methodX.apply(null, [arg1, arg2, arg3]);

如文档中所说:

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

如果你使用的是 ES6,有一个完美的方法来处理这个问题:Spread 运算符

functionName(...args);

Example: it is common to use Function.prototype.apply in cases where you want to use an array as arguments to a function.

function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction.apply(null, args);

With ES6 spread you can now write the above as:

function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction(...args);

Any argument in the argument list can use the spread syntax and it can be used multiple times.

function myFunction(v, w, x, y, z) { } var args = [0, 1]; myFunction(-1, ...args, 2, ...[3]);

详情请参考here

工作fiddlehere