ES13新增的数组方法 at(), 可以通过传入下标直接获取数组对应小标的内容,案例如下:
const arr = [1,2,3,4,5];
arr.at(0) // 1
arr.at(1) // 2
arr.at(-1) // 5
因为特性比较新,所以推荐加上兼容方法,以免低版本浏览器不兼容:
// at方法的兼容函数
if (!Array.prototype.at) {
Array.prototype.at = function (index) {
// 处理负数索引
index = index >= 0 ? index : this.length + index;
// 检查索引是否越界
if (index < 0 || index >= this.length) {
return undefined;
}
return this[index];
};
}