Spread Syntax vs Rest Parameter in ES2015 / ES6

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

    Javascript's three dots ( ... ) operator can be used in two different ways:

    1. Rest parameter: collects all remaining elements into an array.

    var days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
    const [sat, sun, ...weekdays] = days;
    console.log(sat); // "Sat"
    console.log(sun); // "Sun"
    console.log(weekdays); // ["Mon", "Tue", "Wed", "Thu", "Fri"]

    1. Spread operator: allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements.

    var weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
    var days = [...weekdays, "Sat", "Sun"]; 
    console.log(days) // ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

    Note that the spread operator can be the first element, but the rest parameter needs to be the last to collect the rest elements .

提交回复
热议问题