如何使用展開運算符 (...)

學習如何在 JavaScript 中使用三點運算符 (...),也稱為展開運算符。

展開運算符(spread operator)

JavaScript 的展開運算符 (...) 可以將一個可迭代的對象(如數組)擴展為更多的元素。

這允許我們快速地將現有數組的全部或部分復制到另一個數組中:

實例

使用 JavaScript 中的展開運算符來合并兩個數組

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

親自試一試

展開運算符經常用于從數組中提取所需的部分:

實例

將 numbers 數組的第一項和第二項分配給變量,并將剩余的部分放入另一個數組中:

const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;

親自試一試

我們也可以在對象上使用展開運算符:

實例

const myVehicle = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'red'
}
const updateMyVehicle = {
  type: 'car',
  year: 2021,
  color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

親自試一試

請注意,不匹配的屬性被合并了,但是匹配的屬性 color 被最后傳入的對象 updateMyVehicle 覆蓋了。最終的顏色現在是黃色。

相關頁面

教程:JavaScript ES6