JavaScript: Spread Operator

29th July 2019 at 5:20pm
JavaScript: Operator

Spread operator (...) 跟 Python 的 unpack (*) 非常类似。参考 MDN 上的这些文档,讲得简单明了而且有很多实用例子:

// 用于 array literals
[...iterableObj, 4, 5, 6]

// 用于函数调用
myFunction(...iterableObj);

// 用于函数声明
function(a, b, ...theArgs) {
  // ...
}

// rest parameters 可以被 destructure
function f(...[a, b, c]) {
  return a + b + c;
}

f(1)          // NaN (b and c are undefined)
f(1, 2, 3)    // 6
f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)

// 用于变量赋值(array / object 展开)
var a, b, rest;
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

({a, b} = {a:10, b:20});
console.log(a); // 10
console.log(b); // 20

// ES2016 - not implemented in Firefox 47a01
({a, b, ...rest} = {a:10, b:20, c:30, d:40});