このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

TypedArray.prototype.at()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2022年3月⁩.

at()TypedArray インスタンスのメソッドで整数値を受け取り、そのインデックスにある項目を返します。整数値には正の整数と負の整数が使用できます。負の整数の場合は、この型付き配列の末尾の項目から前に数えます。このメソッドは Array.prototype.at() と同じアルゴリズムです。

試してみましょう

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

let index = 1;

console.log(`An index of ${index} returns the item ${int8.at(index)}`);
// Expected output: "An index of 1 returns the item 10"

index = -2;

console.log(`An index of ${index} returns the item ${int8.at(index)}`);
// Expected output: "An index of -2 returns the item 40"

構文

js
at(index)

引数

index

返される型付き配列要素のゼロ基点のインデックスで、整数に変換されます。負の添字を使用した場合は、型付き配列の末尾から逆に数えた位置です。 index < 0 であれば、 index + array.length がアクセスされます。

返値

指定されたインデックスに一致する型付き配列の要素です。 index < -array.length または index >= array.length の場合は、対応するプロパティにアクセスしようとせずに常に undefined を返します。

解説

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

型付き配列の最後の値を返す

次の例は、指定した配列の中で最後に見つかった要素を返す関数を提供する例です。

js
const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);

// 指定された配列の最後の項目を返す関数です。
function returnLast(arr) {
  return arr.at(-1);
}

const lastItem = returnLast(uint8);
console.log(lastItem); // 18

メソッドの比較

ここでは、 TypedArray の最後から 2 番目の項目を選択するさまざまな方法を比較しています。以下に示すどの方法も有効ですが、at() メソッドの簡潔さと読みやすさが際立っています。

js
// Our typed array with values
const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]);

// Using length property
const lengthWay = uint8[uint8.length - 2];
console.log(lengthWay); // 11

// Using slice() method. Note an array is returned
const sliceWay = uint8.slice(-2, -1);
console.log(sliceWay[0]); // 11

// Using at() method
const atWay = uint8.at(-2);
console.log(atWay); // 11

仕様書

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

ブラウザーの互換性

関連情報