在不知道快速获取数组最后一个值时,我们的写法是:

let arr = [1,2,3,5,1,2,3,6,5,4,1,100];
let index = arr.length - 1 
console.log(arr[index]) 

我们需要获取它的长度再去减1,然后通过下标得到最后一个值,本人认为这样的写法会比较麻烦,其实我们可以使用另外一种方式 = 》Array.prototype.at()

at() 方法接收一个整数值并返回该索引的项目,允许正数和负数。负整数从数组中的最后一个项目开始倒数。

方括号符号没有问题。例如,array[0]将返回第一个项目。然而,对于后面的项目,不要使用array.length,例如,对于最后一个项目,可以调用array.at(-1)(参见以下示例)

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of ${index} item returned is ${array1.at(index)}`);
// expected output: "Using an index of -2 item returned is 130"

语法 at(index) Copy to Clipboard

参数 index要返回的数组元素的索引(位置)。当传递负数时,支持从数组末端开始的相对索引;也就是说,如果使用负数,返回的元素将从数组的末端开始倒数。

返回值 匹配给定索引的数组中的元素。如果找不到指定的索引,则返回undefined。

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐