TypedArray.prototype.forEach()

Baseline Widely available

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

forEach()TypedArray インスタンスのメソッドで、型付き配列の要素ごとに一度与えられた関数を実行します。このメソッドのアルゴリズムは Array.prototype.forEach() と同じです。

試してみましょう

構文

js
forEach(callbackFn)
forEach(callbackFn, thisArg)

引数

callbackFn

型付き配列のそれぞれの要素に対して実行する関数です。返値は破棄されます。この関数は以下の引数で呼び出されます。

element

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

index

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

array

forEach() が呼び出されている型付き配列です。

thisArg 省略可

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

返値

なし (undefined)。

解説

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

型付き配列の内容をログに出力する

以下のコードは型付き配列内の各要素を 1 行ずつ出力します。

js
function logArrayElements(element, index, array) {
  console.log(`a[${index}] = ${element}`);
}

new Uint8Array([0, 1, 2, 3]).forEach(logArrayElements);
// 出力:
// a[0] = 0
// a[1] = 1
// a[2] = 2
// a[3] = 3

仕様書

Specification
ECMAScript Language Specification
# sec-%typedarray%.prototype.foreach

ブラウザーの互換性

BCD tables only load in the browser

関連情報