JavaScript-延展運算子

延展運算子

延展運算子由三個點(…)組成,具備多種功能。

首先延展運算子的其中一個功能,可以協助我們結合兩個陣列,產生一個新陣列,跟 JavaScript 的陣列方法 concat 一樣。

用延展運算子:

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
comments powered by Disqus