【问题标题】:Passing array of arguments for a function which expects N number of arguments为需要 N 个参数的函数传递参数数组
【发布时间】:2017-01-02 16:04:24
【问题描述】:

基本上我想做的和这个类似;

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。

【问题讨论】:

标签: javascript jquery ajax .when


【解决方案1】:

您可以为此使用函数apply

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

就像文档中所说的那样:

apply() 方法调用具有给定 this 值的函数,并且 以数组(或类似数组的对象)形式提供的参数。

【讨论】:

    【解决方案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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2012-01-17
    • 2021-02-23
    相关资源
    最近更新 更多