Spread Syntax vs Rest Parameter in ES2015 / ES6

2020-01-29 03:19发布

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

9条回答
唯我独甜
2楼-- · 2020-01-29 04:01

When using spread, you are expanding a single variable into more:

var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];

When using rest arguments, you are collapsing all remaining arguments of a function into one array:

function sum( first, ...others ) {
    for ( var i = 0; i < others.length; i++ )
        first += others[i];
    return first;
}
console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;

查看更多
你好瞎i
3楼-- · 2020-01-29 04:08

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 .

查看更多
虎瘦雄心在
4楼-- · 2020-01-29 04:09

When we see "..." in the code, it is either rest parameters or the spread operator.

There’s an easy way to distinguish between them:

When ... is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list into the array. When ... occurs in a function call or alike, it’s called a “spread operator” and expands an array into the list. Use patterns:

Rest parameters are used to create functions that accept any number of arguments. The spread operator is used to pass an array to functions that normally require a list of many arguments. Together they help to travel between a list and an array of parameters with ease. For more information about this click here

查看更多
登录 后发表回答