TypedArray.prototype.findIndex() - JavaScript | MDN

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2016年9月.

findIndex()TypedArray インスタンスのメソッドで、指定されたテスト関数を満たす型付き配列の最初の要素のインデックスを返します。テスト関数を満たす要素がない場合、 -1 を返します。このメソッドのアルゴリズムは Array.prototype.findIndex() と同じです。

試してみましょう

function isNegative(element, index, array) {
  return element < 0;
}

const int8 = new Int8Array([10, -20, 30, -40, 50]);

console.log(int8.findIndex(isNegative));
// 予想される結果: 1

構文

js

findIndex(callbackFn)
findIndex(callbackFn, thisArg)

引数

callbackFn

配列のそれぞれの要素に対して実行する関数です。要素がテストに合格した場合は真値を返し、そうでなければ偽値を返す必要があります。この関数は以下の引数で呼び出されます。

element

現在処理されている型付き配列の要素です。

index

現在処理されている型付き配列の要素のインデックスです。

array

findIndex() が実行されている型付き配列です。

thisArg 省略可

callbackFn を実行する際に this として使用する値。反復処理メソッドを参照してください。

返値

テストを通った配列の要素の位置を返します。それ以外の場合は、 -1 を返します。

解説

詳細については、 Array.prototype.findIndex() をご覧ください。このメソッドは汎用的ではなく、型付き配列インスタンスに対してのみ呼び出すことができます。

型付き配列内の最初の素数の位置を検索

次の例では、型付き配列の中で素数の入った最初の素数の要素の位置を返し、素数が見つからなかった場合は -1 を返します。

js

function isPrime(n) {
  if (n < 2) {
    return false;
  }
  if (n % 2 === 0) {
    return n === 2;
  }
  for (let factor = 3; factor * factor <= n; factor += 2) {
    if (n % factor === 0) {
      return false;
    }
  }
  return true;
}

const uint8 = new Uint8Array([4, 6, 8, 12]);
const uint16 = new Uint16Array([4, 6, 7, 12]);

console.log(uint8.findIndex(isPrime)); // -1, not found
console.log(uint16.findIndex(isPrime)); // 2

メモ: この isPrime() の実装はデモンストレーション用です。実際のアプリケーションでは、繰り返し計算を避けることができますので、エラトステネスの篩のような高度な記憶化アルゴリズムを使用することをお勧めします。

仕様書

Specification
ECMAScript® 2026 Language Specification
# sec-%typedarray%.prototype.findindex

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.