Is it possible to send a variable number of arguments to a JavaScript function?

后端 未结 12 1020
[愿得一人]
[愿得一人] 2020-11-22 10:51

Is it possible to send a variable number of arguments to a JavaScript function, from an array?

var arr = [\'a\',\'b\',\'c\']

var func = function()
{
    //         


        
12条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 11:07

    The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:

    var arr = ['quick', 'brown', 'lazy'];
    
    var sprintf = function(str, ...args)
    {
        for (arg of args) {
            str = str.replace(/%s/, arg);
        }
        return str;
    }
    
    sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
    sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
    

    Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr); is not yet supported. You can find an ES6 compatibility table here.

    Note also the use of for...of, another ES6 addition. Using for...in for arrays is a bad idea.

提交回复
热议问题