ES6
.at() method for arrays
How do you read the tail element of the array? Yes, we need to read with “array.length — 1” as a subscript.
const array = [ 1, 2, 3, 4, 5
const lastEle = array[ array.length - 1 ] // 5
// You can't read like that
const lastEle = array[ - 1 ] // undefined]
ES2022 provides an array method called?at, which may be a small change, but it can greatly improve the readability of the code.
The?at?method can take positive or negative numbers, and that will determine whether it starts reading elements from the head or the tail of the array.
const array = [ 1, 2, 3, 4, 5
const lastEle = array.at(-1) // 5
const firstEle = array.at(0) // 1]