【问题标题】:What is the meaning of "foo(...arg)" (three dots in a function call)?“foo(...arg)”(函数调用中的三个点)是什么意思?
【发布时间】:2017-06-26 08:53:53
【问题描述】:

有人能说出“Intro to Angular”示例中以下代码中的“...”是什么吗?

getHeroes() {
    this.backend.getAll(Hero).then( (heroes: Hero[]) => {
      this.logger.log(`Fetched ${heroes.length} heroes.`);
      this.heroes.push(...heroes); // fill cache
    });

【问题讨论】:

标签: javascript


【解决方案1】:

根据问题的标题,在函数声明(括号内)中使用 ... 是 rest operator 或 rest参数,为了帮助我们创建更灵活的函数,ES6引入了函数参数的rest参数。

使用其余参数,您可以创建带有可变数量参数的函数。这些参数存储在一个数组中,以后可以从函数内部访问。

示例:1

function foo(...args) {
  return "You have passed " + args.length + " arguments.";
}

console.log(foo(0, 1, 2,4)); // You have passed 4 arguments.
console.log(foo("hello", null, [1, 2], { })); // You have passed 4 arguments.

示例 2:

function foo(...args){
     args.forEach(function(arg){
        console.log(arg);
     })
   }

   foo(2,3,4,5,6);

rest 参数消除了检查args 数组的需要,并允许我们在参数数组上应用map()、filter()、reduce() 和其他数组高阶函数。

...运算符的其他用例:

  1. 用作spread operator,与rest operator相反。

    const arr = [6, 89, 3, 45]; const maximum= Math.max(...arr); console.log(maximum);

  2. ... 运算符用于非常轻松地复制数组或对象,并且分别在 javascript 框架和库(如 angular 和 react)中非常有用。

    const arr1 = [1,2,3,4];
    const arr2 = [...arr1];
    console.log(arr2);//  [1,2,3,4];
    
    const obj1 = {
      name:'john',
      age:25
    }
    
    const obj2 = {...obj1};
    console.log(obj2); // Now obj2 is new object and is copy of obj1 (non-mutated 
    way)
    

【讨论】:

    【解决方案2】:

    它是原始数组的副本

    let args = [7, 3, 8];
    var [h] = args.reverse(); // args is now 8, 3, 7
    

    而

    var [h] = [...args].reverse(); // args is still 7, 3, 8
    

    也可以用来指定数组的剩余值

    var [first, ...rest] = args; // first = 7, rest = [3, 8]
    

    【讨论】:

      【解决方案3】:

      这是一个名为 Rest Parameters 的 JavaScript 功能。 通过使用它,您的函数可以接受任意数量的参数。 您将三个点放在参数之前(没有空格字符),该机制会为您展开它,就好像它是几个参数的列表一样。 在 Eloquent Javascript 中你有一个很好的例子。

      let numbers = [5, 1, 7];
      console.log(max(...numbers));
      // -> 7
      

      【讨论】:

        【解决方案4】:

        这与 jQuery 或 Angular 无关。这是 ES2015 中引入的功能。

        ...doesn't actually have an official name 的这种特殊用法。与其他用途一致的名称将是“传播参数”(通用术语是"spread syntax")。它“爆炸”(传播)一个 iterable 并将每个值作为参数传递给函数。您的示例相当于:

        this.heroes.push.apply(this.heroes, Array.from(heroes));
        

        除了更简洁之外,... 的另一个优点是它可以更容易地与其他具体参数一起使用:

        func(first, second, ...theRest);
        
        // as opposed to the following or something similar:
         func.apply(null, [first, second].concat(Array.from(heroes)));
        

        【讨论】:

          猜你喜欢
          • 2017-06-30
          • 2017-04-28
          • 2015-03-17
          • 1970-01-01
          • 2021-11-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多