masanos note

Array.prototype.at()

2021-01-31
icon

The at() method takes an integer value and allows positive and negative integers.
Useful for getting the n-th value from the front of the array, the nth value from the end of an array.

Target Array

const arr = ['banana', 'orange', 'apple', 'cherry', 'kiwi']


n-th value from the front of the array

console.log(arr.at(0))
// "banana"

console.log(arr.at(1))
//  "orange"

console.log(arr.at(2))
// "apple"


the n-th value from the end of an array

console.log(arr.at(-1))
// "kiwi"

console.log(arr.at(-2))
// "cherry"

console.log(arr.at(-3))
// "apple"


Not number case

console.log(arr.at(null))
console.log(arr.at('a'))
console.log(arr.at('b'))
console.log(arr.at([]))
console.log(arr.at({}))
console.log(arr.at(undefined))

// "banana"


Boolean

console.log(arr.at(true))
// "orange"

console.log(arr.at(false))
// "banana"


Ref.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
https://codepen.io/masanos/pen/YzvRgNK?editors=0012

A record of the development is left in a web note.
Masanos
I want to make the world I see happy. Little by little, I am preparing to start a business. Thank you for your support.
Buy Me A Coffee
Copyright© masanos All Rights Reserved.