React ES6 展開運算子
展開運算子
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
覆蓋了。最終的 color 現在是 yellow。