“foo(...arg)”(函数调用中的三个点)的含义是什么?

10

有人能告诉我在“Angular入门”示例中下面代码中的“…”是什么吗?

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

1
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator - Shilly
4个回答

11

这与jQuery或Angular无关,它是在ES2015中引入的一个特性。

...的这种特殊用法实际上没有官方名称。与其他用法相一致的名称应为“扩展参数”(通用术语为“扩展语法”)。它“展开”(扩展)一个可迭代对象并将每个值作为参数传递给函数。您的示例等同于:

this.heroes.push.apply(this.heroes, Array.from(heroes));
< p >除了更加简洁外,... 在这里的另一个优点是它可以更轻松地与其他具体参数一起使用:< /p>
func(first, second, ...theRest);

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

3

这是JavaScript的一个功能,称为Rest参数。使用它,您的函数可以接受任意数量的参数。您只需在参数前面(没有空格字符)放置三个点,并且该机制会将其展开,就像它是几个参数列表一样。在《JavaScript精解》中,您可以找到一个很好的例子。

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

1
这是原始数组的副本。
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]

0
根据问题标题,函数声明中括号内使用的...rest操作符rest参数。为了帮助我们创建更灵活的函数,ES6引入了函数参数的rest参数。
使用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);

剩余参数消除了检查 args 数组的需要,使我们能够在参数数组上应用 map()、filter()、reduce() 和其他数组高阶函数。

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

  1. 被用作展开运算符,它是剩余运算符的反向操作。

    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); // 现在 obj2 是一个新对象,并且是 obj1 的副本(非变异方式)
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接