0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】IF文で「指定した変数がいずれかの値と一致したらTRUE」条件を記述

Posted at

ちょっと面白かったので、メモを兼ねて投稿します。

コードの実例

以下のような、一つの変数しか使っていないOR条件のIF文をもっと短く書けないかなぁと思いました。

if (value === 1 || value === 2 || value === 3
  || value == 4 || value == 5 || value == 6
  || value == 7 || value == 8 || value == 9) {
  // 処理
}

以下のように、配列にすると短く書けますね。

if ([1, 2, 3, 4, 5, 6, 7, 8, 9].includes(value)) {
  // 処理
}

ただしIEではincludes()メソッドはサポートしていないようです。
そこで、代わりにindexOf()メソッドを使う手もあります。

if ([1, 2, 3, 4, 5, 6, 7, 8, 9].indexOf(value) !== -1) {
  // 処理
}

これならIE11では動くはずです。
どのような書き方にせよ、他の人がぱっと見で理解できるのが一番ですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?