LoginSignup
0
0

More than 1 year has passed since last update.

複数の条件式がある分岐のincludesを使った便利な書き方

Last updated at Posted at 2022-05-19

複数の条件式がある場合のすっきりした書き方です。

例えば、以下の様な複数の条件式に当てはまる場合に処理をしたい場合、自分は||で繋げてベタ書いてしまいがちです。

if (
  key === 'exclude_completed' ||
  key === 'exclude_checked' ||
  key === 'exclude_assigned'
) {
  //処理をする
}

レビューで arrayのincludesメソッド を使う方がいいですよって指摘を受けて、いつも忘れてしまうので備忘録のため記事に残そうと思いました。

if (
  ['exclude_completed', 'exclude_checked', 'exclude_assigned'].includes(key)
) {
  //処理をする
}

//配列部分は外に切り出してさらにスッキリさせてもいいですね。
const array = ['exclude_completed', 'exclude_checked', 'exclude_assigned'];

if ( array.includes(key) ) {
  //処理をする
}

includesの詳しい解説はこちら

[配列].includes(配列の中で探したい値)
配列に探したい値があるかチェックして、あればtrue、なければfalseが返る。

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

console.log(array1.includes(4));
// expected output: false

と今回はincludesを使った便利なtipsでした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0