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() は Array インスタンスのメソッドで、整数値を受け取り、そのインデックスにある項目を返します。正の整数値と負の整数値が使用できます。負の整数は、配列の最後の項目から前へ数えます。
at()
Array
const array = [5, 12, 8, 130, 44]; let index = 2; console.log(`${index} のインデックスは ${array.at(index)} を返します`); // 予想される結果: "2 のインデックスは 8 を返します" index = -2; console.log(`${index} のインデックスは ${array.at(index)} を返します`); // 予想される結果: "-2 のインデックスは 130 を返します"
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
at() メソッドは、index が負の整数でない場合、ブラケット記法と等価です。例えば、array[0] と array.at(0) は、どちらも最初の項目を返します。しかし、配列の末尾から要素を数える場合、 Python や R のように array[-1] を使用することはできません。角括弧内の値はすべて文字列プロパティとしてリテラルで扱われるため、結局、配列のインデックスではなく通常の文字列プロパティである array["-1"] を読むことになります。
array[0]
array.at(0)
array[-1]
array["-1"]
通常、length にアクセスし、そこからインデックスを計算します。例えば、 array[array.length - 1] のようになります。 at() メソッドでは相対インデックスが可能なので、これを短縮して array.at(-1) とすることができます。
length
array[array.length - 1]
array.at(-1)
at() と with() を組み合わせることで、負のインデックスを用いた配列の読み取りと書き込みが(それぞれ)できます。
with()
at() メソッドは汎用的です。this 値に length プロパティと整数キーのプロパティがあることだけを期待します。
this
以下の例は、指定された配列の中で最後に見つかった要素を返す関数を提供します。
// 項目付きの配列 const cart = ["りんご", "バナナ", "なし"]; // 指定された配列の最後の項目を返す関数 function returnLast(arr) { return arr.at(-1); } // 配列 'cart' の最後の項⽬を取得する const item1 = returnLast(cart); console.log(item1); // 'なし' // 配列 'cart' に商品を追加 cart.push("みかん"); const item2 = returnLast(cart); console.log(item2); // 'みかん'
この例では、 Array の最後から 1 つ目の項目を選択するさまざまな方法を比較しています。以下に示すどの方法も有効ですが、at() メソッドの簡潔さと読みやすさが際立っています。
// 項目付きの配列 const colors = ["red", "green", "blue"]; // length プロパティの使用 const lengthWay = colors[colors.length - 2]; console.log(lengthWay); // 'green' // slice() メソッドを使用。配列を返すことに注意。 const sliceWay = colors.slice(-2, -1); console.log(sliceWay[0]); // 'green' // at() メソッドを使用 const atWay = colors.at(-2); console.log(atWay); // 'green'
at() メソッドは、this の length プロパティを読み込んで、アクセスする添字を計算します。
const arrayLike = { length: 2, 0: "a", 1: "b", 2: "c", // length が 2 なので at() からは無視される }; console.log(Array.prototype.at.call(arrayLike, 0)); // "a" console.log(Array.prototype.at.call(arrayLike, 2)); // undefined
Enable JavaScript to view this browser compatibility table.
Array.prototype.at
core-js
Array.prototype.findIndex()
Array.prototype.indexOf()
Array.prototype.with()
TypedArray.prototype.at()
String.prototype.at()