388
208

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でx === 'a' || x === 'b' || x === 'c' || ...をシュッとさせる

Last updated at Posted at 2020-06-16

JavaScriptで次のような||演算子が繰り返し使われたコードを、より簡潔に書く方法を紹介します。

if (
  x === 'a' || 
  x === 'b' || 
  x === 'c' || 
  x === 'd' || 
  x === 'e'
) {
  console.log('ok')
}

このような文字列比較の繰り返しは、Array.prototype.includes()を使うと、簡潔に書くことができます:

if (['a', 'b', 'c', 'd', 'e'].includes(x)) {
  console.log('ok')
}

Array.prototype.includes()はES2016で導入されました。

参考文献


最後までお読みくださりありがとうございました。Twitterでは、Qiitaに書かない技術ネタなどもツイートしているので、よかったらフォローしてもらえると嬉しいです:relieved:Twitter@suin

388
208
18

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
388
208

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?