延展運算子由三個點(…)組成,具備多種功能。
用延展運算子:
const flowers = ["Lily", "Rose", "Sunflower"];
const plant = ["cactus", "Snake Plant"];
const decorate = [...flowers, ...plant];
console.log(decorate); //[ 'Lily', 'Rose', 'Sunflower', 'cactus', 'Snake Plant' ]
用 concat:
const flowers = ["Lily", "Rose", "Sunflower"];
const plant = ["cactus", "Snake Plant"];
console.log(flowers.concat(plant));
//[ 'Lily', 'Rose', 'Sunflower', 'cactus', 'Snake Plant' ]
不使用延展運算子,雖然取出的值是正確的,但原本的陣列順序被影響了:
const flowers = ["Lily", "Rose", "Sunflower"];
const [last] = flowers.reverse();
console.log(last); //Sunflower
console.log(flowers); //[ 'Sunflower', 'Rose', 'Lily' ]
使用延展運算子,會先複製一個新陣列再進行反轉,所以不會影響到原本陣列:
const flowers = ["Lily", "Rose", "Sunflower"];
const [last] = [...flowers].reverse();
console.log(last); //Sunflower
console.log(flowers); //[ 'Lily', 'Rose', 'Sunflower' ]
const [White, ...Red] = ["Lily", "Rose", "Peony"];
console.log(White, Red); //Lily [ 'Rose', 'Peony' ]
const morning = {
breakfast: "toast",
lunch: "boxed meal",
};
const dinner = "instant noodles";
const backpackingMeals = {
...morning,
dinner,
};
console.log(backpackingMeals);
//{ breakfast: 'toast', lunch: 'boxed meal', dinner: 'instant noodles' }
使用在呼叫函式:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers)); //6
或是當函式的參數:
function sum(...numbers) {
let [x, ...other] = numbers;
let [y, z] = other;
return x + y + z;
}
console.log(sum(1, 2, 3)); //6