#javascript statement

1. 使用 Array.includes 來處理多重條件

// 原始寫法
function test(fruit) {
  // 條件語句
  if (fruit === "apple" || fruit === "strawberry") {
    console.log("red fruit");
  }
}

乍看之下,寫法沒什麼錯誤。可是當我們有更多紅色水果的選項時,如 cherry(櫻桃)和 cranberries(蔓越莓),難道我們要增加更多的 || 邏輯運算子來判斷?

我們用 Array.includes 來改寫一次上面的判斷式:

// 改寫後
function test(fruit) {
  // 將選項提取出來,放入陣列當中
  const redFruits = ["apple", "strawberry", "cherry", "cranberries"];
  if (redFruits.includes("apple")) {
    console.log("red fruit");
  }
}

閱讀我吧!