JavaScript 學習筆記-Array.at

Eason Lin
Jul 1, 2021

--

今天偶然在一篇 Medium 文章看到 Array.at 的介紹,想說是一個從來沒聽過的方法,就查閱了一下 MDN 並決定記錄在這邊。

Array.at 方法接收一個 integer 作為參數,並會回傳陣列中對應索引的值,其可以傳入正數,亦可傳入負數。例如:

const ary = [2,4,6,8,10]ary.at(1)  // 4ary.at(-1) // 10ary.at(5)  // undefined

眼尖的人可能會發現,這跟使用 Bracket notation 去取陣列中的值不是很像嗎?差別就在於當我們嘗試去取陣列中最尾端的值,可能是使用:

const ary = [2,4,6,8,10]
const lastIndex = ary.length - 1
ary[lastIndex] // 10

但若是使用 Array.at,其實只要使用 ary.at(-1) 就能輕鬆辦到。

目前這個方法的提案已經到了 Stage3 (Candidate) 階段,如果最後通過 Stage4 成為了新的標準,相信一定能對 JS 開發者們有很大幫助。

關於 Array.at 就記錄到這邊,希望能幫助到路過的你。若內文有任何錯誤,也請不吝提出,謝謝~

References:

--

--

Eason Lin
Eason Lin

Written by Eason Lin

Frontend Web Developer | Books

No responses yet