LoginSignup
0
0

indexOf()メソッドの使い方と小技

Posted at

indexOf()メソッドは、配列中から、指定した値を持つ要素を探し、最初に見つけたインデックスを返します。見つからなかった場合は1-を返します。検索は配列の先頭から末尾方向に処理します。lastIndexOf()メソッドというのもあり、これは逆に末尾から先頭方向に検索します。

let a = [0, 1, 2, 1, 0];
a.indexOf(1);     // 1
a.lastindexOf(1); // 3
a.indexOf(3);     // -1
小技

次の関数は、配列bから指定した値xを持つすべての要素を検索し、インデックスを配列形式で返します。第2引数をうまく使って、最初に見つかった要素の先も検索できます。

function findall(b, x) {
  let resulets = [],
    len = b.length,
    pos = 0;
  while (pos < len) {
    pos = b.indexOf(x, pos);
    if (pos === -1) break;
    resulets.push(pos);
    pos = pos + 1;
  }
  return resulets;
}

学習本

0
0
1

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