Spread Syntax vs Rest Parameter in ES2015 / ES6

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

    From: Ved Antani, Stoyan Stefanov Book “Object-Oriented JavaScript - Third Edition.” :

    Rest parameters

    ES6 introduces rest parameters. Rest parameters allow us to send an arbitrary number of parameters to a function in the form of an array. Rest parameter can only be the last one in the list of parameters, and there can only be one rest parameter. Putting a rest operator(...) before the last formal parameter indicates that parameter is a rest parameter. The following example shows adding a rest operator before the last formal parameter:

    function sayThings(tone, ...quotes){ 
      console.log(Array.isArray(quotes)); //true 
      console.log(`In ${tone} voice, I say ${quotes}`) 
    } 
    sayThings("Morgan Freeman","Something serious"," 
     Imploding Universe"," Amen"); 
    //In Morgan Freeman voice, I say Something serious,
     Imploding Universe,Amen 
    

    The first parameter passed to the function is received in tone, while the rest of the parameters are received as an array. Variable arguments (var-args) have been part of several other languages and a welcome edition to ES6. Rest parameters can replace the slightly controversial arguments variable. The major difference between rest parameters and the arguments variable is that the rest parameters are real arrays. All array methods are available to rest parameters.

    Spread operators

    A spread operator looks exactly like a rest operator but performs the exact opposite function. Spread operators are used while providing arguments while calling a function or defining an array. The spread operator takes an array and splits its element into individual variables. The following example illustrates how the spread operator provides a much clearer syntax while calling functions that take an array as an argument:

    function sumAll(a,b,c){ 
      return a+b+c 
    } 
    var numbers = [6,7,8] 
    //ES5 way of passing array as an argument of a function 
    console.log(sumAll.apply(null,numbers)); //21 
    //ES6 Spread operator 
    console.log(sumAll(...numbers))//21 
    

提交回复
热议问题