HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
All web technology
Learn web development
Discover our tools
Get to know MDN better
このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。
View in English Always switch to English
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() と同じアルゴリズムです。
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)}`); // 予想される結果: "An index of 1 returns the item 10" index = -2; console.log(`An index of ${index} returns the item ${int8.at(index)}`); // 予想される結果: "An index of -2 returns the item 40"
at(index)
index
返される型付き配列要素のゼロ基点のインデックスで、整数に変換されます。負の添字を使用した場合は、型付き配列の末尾から逆に数えた位置です。 index < 0 であれば、 index + array.length がアクセスされます。
index < 0
index + array.length
指定されたインデックスに一致する型付き配列の要素です。 index < -array.length または index >= array.length の場合は、対応するプロパティにアクセスしようとせずに常に undefined を返します。
index < -array.length
index >= array.length
undefined
詳細は Array.prototype.at() を参照してください。このメソッドは汎用的ではなく、型付き配列インスタンスに対してのみ呼び出すことができます。
次の例は、指定した配列の中で最後に見つかった要素を返す関数を提供する例です。
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() メソッドの簡潔さと読みやすさが際立っています。
// 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
Enable JavaScript to view this browser compatibility table.
TypedArray.prototype.at
core-js
TypedArray.prototype.findIndex()
TypedArray.prototype.indexOf()
TypedArray.prototype.with()
String.prototype.at()