代码之家  ›  专栏  ›  技术社区  ›  David Hellsing

使用参数数组调用函数[重复]

  •  19
  • David Hellsing  · 技术社区  · 15 年前

    例子:

    var fn = function() {
        console.log(arguments);
    }
    
    var args = [1,2,3];
    
    fn(args);
    

    我需要 arguments [1,2,3]

    2 回复  |  直到 9 年前
        1
  •  47
  •   Christian C. Salvadó    5 年前

    自从ES6推出以来,您可以起诉 spread syntax 在函数调用中:

    const args = [1,2,3];
    
    fn(...args);
    
    function fn() {
      console.log(arguments);
    }

    在ES6之前,您需要使用 apply

    var args = [1,2,3];
    fn.apply(null, args);
    
    function fn() {
      console.log(arguments);
    }

    两者都将生成等效的函数调用:

    fn(1,2,3);
    

    注意,我使用 null 作为 例如,它将设置 this 全局对象的关键字( window )里面 fn undefined 在严格模式下。

    另外,你应该知道 arguments 对象不是数组,而是类似数组的对象,它包含与用于调用函数的参数对应的数字索引 length 属性,该属性提供所使用的参数数。

    在ES6中,如果希望以数组形式访问可变数量的参数,还可以使用 rest syntax

    function fn(...args) {
      args.forEach(arg => console.log(arg))
    }
    
    fn(1,2,3)

    在ES6之前,如果您想从 对象,您通常使用 Array.prototype.slice

    function fn() {
      var args = Array.prototype.slice.call(arguments);
      console.log(args);
    }
    
    fn(1,2,3);

    编辑: 对于您的评论,是的,您可以使用 shift 方法并将其返回值设置为上下文( 关键字)在您的函数上:

    fn.apply(args.shift(), args);
    

    如果仍然需要使用所有其他参数调用函数,可以:

    fn.apply(args[0], args);
    

    如果不想更改上下文,可以提取函数中的第一个参数:

    function fn(firstArg, ...args) {
       console.log(args, firstArg);
    }
    
    fn(1, 2, 3, 4)

    在ES5中,这将更加冗长。

    function fn() {
      var args = Array.prototype.slice.call(arguments),
            firstArg = args.shift();
    
      console.log(args, firstArg);
    }
    
    fn(1, 2, 3, 4);
        2
  •  13
  •   Michał Perłakowski    8 年前

    在ECMAScript 6中,可以使用 spread syntax ( ... ) 为此目的。它比其他语言更简单、更容易理解 Function.prototype.apply() .

    const fn = function() {
      console.log(arguments);
    }
    
    const args = [1,2,3];
    
    fn(...args);