新的數組方法:array-at--
JavaScript 數組的索引是從 0 開始的,第一個元素的索引爲 0,最後一個元素的索引等於該數組的長度減 1。
在之前,我們一般使用方括號通過索引訪問數組元素:array[index],如果指定的索引是一個無效值,JavaScript 數組並不會報錯,而是會返回 undefined。
const array = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr[0]) // logs 'this is the first element'
console.log(arr[1]) // logs 'this is the second element'
在大多數情況下,方括號語法是通過正索引訪問數組元素的好方法。
但有時我們希望從末尾而不是從頭開始訪問元素。例如,訪問數組的最後一個元素:
const array = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr[arr.length - 1]) // logs 'this is the last element'
現在,數組提供了一個新的方法來訪問數組元素:Array.prototype.at()。
at() 方法接收一個整數值並返回該索引的項目,允許正數和負數。負整數從數組中的最後一個項目開始倒數。
方括號符號沒有問題,但對於後面的項目,可以調用 array.at(-1),無須再訪問 array.length (參見以下示例):
const array1 = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr.at(0)) // logs 'this is the first element'
console.log(arr.at(-2)) // logs 'this is the second element'
console.log(arr.at(-1)) // logs 'this is the last element'
上面的例子凸顯了 at() 方法的簡潔性和可讀性。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/FDS4D6DkHi4KzwD5dn1yIQ