Spread Syntax vs Rest Parameter in ES2015 / ES6

前端 未结 10 1767
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 10:52

I am confused about the spread syntax and rest parameter in ES2015. Can anybody explain the difference between them with proper examples?

10条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 11:29

    Summary:

    In javascript the ... is overloaded. It performs a different operations based on where the operator is used:

    1. When used in function arguments of a function declaration/expression it will convert the remaining arguments into an array. This variant is called the Rest parameters syntax.
    2. In other cases it will spread out the values of an iterable in places where zero or more arguments (function calls) or elements (array literals) are expected. This variant is called the Spread syntax.

    Example:

    Rest parameter syntax:

    function rest(first, second, ...remainder) {
      console.log(remainder);
    }
    
    // 3, 4 ,5 are the remaining parameters and will be 
    // merged together in to an array called remainder 
    rest(1, 2, 3, 4, 5);

    Spread syntax:

    function sum(x, y, z) {
      return x + y + z;
    }
    
    const numbers = [1, 2, 3];
    
    // the numbers array will be spread over the 
    // x y z parameters in the sum function
    console.log(sum(...numbers));
    
    
    // the numbers array is spread out in the array literal
    // before the elements 4 and 5 are added
    const newNumbers = [...numbers, 4, 5];
    
    console.log(newNumbers);

提交回复
热议问题