Spread Syntax vs Rest Parameter in ES2015 / ES6

前端 未结 10 1818
隐瞒了意图╮
隐瞒了意图╮ 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:11

    considering 3 scenarios

    1] without using any operator

    function add(x, y) {
      return x + y;
    }
    
    add(1, 2, 3, 4, 5) // returns 3  (function will takes first 2 arg only)
    

    2] with rest operator

    function add(...args) {
      let result = 0;
    
      for (let arg of args) result += arg;
    
      return result
    }
    
    add(1) // returns 1
    add(1,2) // returns 3
    add(1, 2, 3, 4, 5) // returns 15
    

    - we can gather any number of arguments into an array

    3] with spread operator

    const arr = ["Joy", "Wangari", "Warugu"];
    const newArr = ["joykare", ...arr];
    
    The value of newArr will be [ 'joykare', 'Joy', 'Wangari', 'Warugu' ]
    

    another one

    function add(a, b, c) {
      return a + b + c ;
    }
    const args = [1, 2, 3];
    
    add(...args);
    
    -We have been using arrays to demonstrate the spread operator, 
    but any iterable also works. So, if we had a 
    string const str = 'joykare', [...str] translates to [ 'j', 'o', 'y', 'k', 'a', 'r', 'e' ]
    

提交回复
热议问题