TypedArray.prototype.findLast()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2022年8月.
findLast() は TypedArray インスタンスのメソッドで、型付き配列を逆順に反復処理し、指定されたテスト関数を満たす最初の要素の値を返します。テスト関数を満たす要素がない場合は undefined を返します。このメソッドのアルゴリズムは Array.prototype.findLast() と同じです。
試してみましょう
function isNegative(element /*, index, array */) {
return element < 0;
}
const int8 = new Int8Array([10, 0, -10, 20, -30, 40, 50]);
console.log(int8.find(isNegative));
// 予想される結果: -30
構文
findLast(callbackFn)
findLast(callbackFn, thisArg)
引数
callbackFn-
配列のそれぞれの要素に対して実行する関数です。要素がテストに合格した場合は真値を返し、そうでなければ偽値を返す必要があります。この関数は以下の引数で呼び出されます。
thisArg省略可-
callbackFnを実行する際にthisとして使用する値。反復処理メソッドを参照してください。
返値
指定されたテスト関数を満たす、最後の(最も大きなインデックスを持つ)型付き配列の要素です。一致する値が見つからない場合は undefined です。
解説
詳細については、 Array.prototype.findLast() をご覧ください。このメソッドは汎用的ではなく、型付き配列インスタンスに対してのみ呼び出すことができます。
例
>型付き配列から最後の素数のインデックスを探す
以下の例では、型付き配列から素数である値のうち、最後の値を返します(素数がない場合は undefined を返します)。
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;
}
let uint8 = new Uint8Array([4, 6, 8, 12]);
console.log(uint8.findLast(isPrime)); // undefined (配列に素数がない)
uint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]);
console.log(uint8.findLast(isPrime)); // 11
メモ:
この isPrime() の実装はデモンストレーション用です。実際のアプリケーションでは、繰り返し計算を避けることができますので、エラトステネスの篩のような高度な記憶化アルゴリズムを使用することをお勧めします。
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-%typedarray%.prototype.findlast> |
ブラウザーの互換性
関連情報
TypedArray.prototype.findLastのポリフィル (core-js)- JavaScript の型付き配列ガイド
TypedArrayTypedArray.prototype.find()TypedArray.prototype.findIndex()TypedArray.prototype.findLastIndex()TypedArray.prototype.includes()TypedArray.prototype.filter()TypedArray.prototype.every()TypedArray.prototype.some()Array.prototype.findLast()