LoginSignup
0
0

More than 1 year has passed since last update.

【javascript】特定の要素が含まれているか検索する | includes()

Posted at

はじめに

ある変数が、複数の値のどれかに存在するかどうかを判定したい時、何も知らず今までずっと以下のように記載していた。

if(testStr == "a" || testStr == "b" || testStr == "c" || ... ){
    ...
}

条件が数えられるほどの数ならこれでもよいが、これが10を超えてきたあたりから正直書くのがだるくなってくる。(またはコードが汚くなってくる)
そこで、このような状況下でコンパクトにコードが書ける方法があることを知ったので、メモ。

内容

includes()メソッドを使用する。

使用例
let okList = ["a", "b", "c", ... ];
if(okList.includes(testStr)){
    ...
}

詳細

条件として認められる要素を配列にし、それに対してincludes()で特定の要素が含まれているか検索する。この時、includes()に引数として渡すのは検索対象となる値であり、検索対象となる配列ではないことに注意。

// これは間違い
testStr.includes(okList);
// これが正解
okList.includes(testStr);

ちなみに、文字列に対しても有効で、その場合は以下のように記載する。

okString = "abcdefg";
okString.includes(testString);
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