JavaScript at() 方法

数组对象:

对于获取数组的最后一个元素,可能平常见得多的就是arr[arr.length - 1],我们其实可以使用at()方法进行获取

接收一个整数值并返回该索引对应的元素:

const arr = [5, 12, 8, 130, 44];
 
let index1 = 2;
strt1 = `索引号为 ${index1} 的值为 ${arr.at(index1)}`;
 
let index2 = -2;
strt2 = `索引号为 ${index2} 的值为 ${arr.at(index2)}`;

console.log(arr.at(-1)) // 倒数第一个值
console.log(arr.at(-2)) // 倒数第二个值
console.log(arr.at(0)) // 正数第一个  
console.log(arr.at(1)) // 正数第二个

注:node14应该是不支持的,不建议使用该方法,但获取数组最后一个元素是很常用的,就应该像上述语法一样简单...

 

非数组对象:

在非数组对象上调用 at():at() 方法读取 this 的 length 属性并计算需要访问的索引。

const arrayLike = {
  length: 2,
  0: "a",
  1: "b",
};
console.log(Array.prototype.at.call(arrayLike, -1)); // "b"

 

posted @ 2023-07-14 17:02  SimoonJia  阅读(186)  评论(0编辑  收藏  举报