[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/at [Back]  [Original]

Array.prototype.at() - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Array.prototype.at()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2022 ..

at() . . .

In this article

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of 2 returns 8"

index = -2;

console.log(`An index of ${index} returns ${array1.at(index)}`);
// Expected output: "An index of -2 returns 130"

js
at(index)

index

() . ; , , .

, . , undefined.

at() . , array[0] array.at(0) . , , array[-1] Python R, . - -1 array["-1"], , .

length , array[array.length - 1]. at() , array.at(-1).

at() generic. , this length .

,

js
//   
const cart = ["apple", "banana", "pear"];

// ,      
function returnLast(arr) {
  return arr.at(-1);
}

//      'cart'
const item1 = returnLast(cart);
console.log(item1); // : 'pear'

//      'cart'
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // : 'orange'

. , at().

js
//    
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()

at() length this .

js
const arrayLike = {
  length: 2,
  0: "a",
  1: "b",
};
console.log(Array.prototype.at.call(arrayLike, -1)); // "b"

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.at


Web Proxy Viewer  |  New URL  |  Original Page