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

时间:2016-08-26 05:00:32

标签: javascript jquery ajax .when

基本上我想做的就是这个;

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.")
        }
    );
}

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

2 个答案:

答案 0 :(得分:4)

您可以使用函数apply

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

就像在文档中说的那样:

  

apply()方法调用一个给定此值的函数   作为数组(或类数组对象)提供的参数。

答案 1 :(得分:2)

如果您正在使用ES6,那么有一种完美的方法可以解决这个问题:Spread运算符

functionName(...args);
  

示例:在其中使用Function.prototype.apply的情况很常见   你想使用数组作为函数的参数。

     

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

     

通过ES6传播,您现在可以将上述内容写为:

     

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

     

参数列表中的任何参数都可以使用扩展语法,并且可以多次使用。

     

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

请参阅here了解详情

工作小提琴here

相关问题