26
15

More than 5 years have passed since last update.

JavaScriptで「条件のどれかに一致」を(少しでも)簡単に書きたい

Last updated at Posted at 2019-02-03

始めに

分岐の条件がいつの間にか増えていき、最終的に書いた本人がしんどくなる事がありました。
そういうコードは、コメントを残してもつらいです。
また保守もしんどくなります。

今回直したのはこんな条件です。

before

// xが判定したいもの
if(x==='hoge' || x==='huga' || x==='piyo'){
  statement
}

・・・最初は1つでしたが、どんどん増えてこうなりました。

こちらの投稿を参考に直しました。
https://qiita.com/yassh/items/12b7e685dc35824819f9

after

const conds = ['hoge', 'huga', 'piyo'];
if(conds.includes(x)){
  statement1
}else{
  statement2
}

使用しているメソッド

Array.prototype.includes()
これは、配列に特定の要素が含まれているかを true または false で返します

// 例
['condition-1', 'condition-2', 'condition-3'].includes('比較対象');

// 返り値はboolean

見通しが良くなったのと、後の保守が楽になりそうです。
もちろん条件次第で使えない場合があるので、そこは臨機応変に使い分けたいと思います。

参考

https://qiita.com/yassh/items/12b7e685dc35824819f9
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

26
15
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
26
15