-
Notifications
You must be signed in to change notification settings - Fork 3
Open
Labels
Description
JS 代码简洁之道 - 数组末尾索引
js 中没有提供直接获取数组末尾索引的方式 (如 python 中可以取 -1)。
通常我们取数组末尾一般要获取数组的长度:
const arr = [1, 2, 3, 4]
const last = arr[arr.length - 1]
但是该行代码看起来及其冗长,尤其是当要频繁获取多个数组末尾索引时。
我们可以用 Array
内置方法可取 -1
索引的特性:
const arr = [1, 2, 3, 4]
const last = arr.slice(-1)[0]
arr.slice()
返回的是数组本身,因此需要通过[0]
来获取最终的值
2021-06-19 更新
若需要频繁获取某一数组的最后一个值,可以利用 Proxy 代理 get 方法:
const arr = [1, 2, 3, 4, 5]
let handler = {
get: function (target, propKey) {
// 数组 key 值为 string 类型的数字,需要转化
const idx = Number(propKey);
return (idx < 0) ? target[target.length + idx] : target[idx]
}
}
const newArr = new Proxy(arr, handler);
console.log(newArr[-1]); // 5
console.log(newArr[0]); // 1
实践中发现,代理数组后所返回的 proxy 代理对象,在调用数组方法时会出现某些问题,暂未找到解决方法,因此现提倡用第一种方式获取数组末尾索引。