JavaScript获取数组最后一个元素的五种方法及性能对比

作者:沉舟时间:2026-10-30 22:35:33浏览:665

本文详细解析了JavaScript中获取数组最后一个元素的五种常用方法,包括利用length属性、slice截取、pop弹出、ES2022新增的at方法以及reverse反转。通过console.time系列函数进行实际代码执行效率测试,对比各方法的耗时差异,发现at()方法在速度上表现最佳,为开发者提供高效处理数组数据的参考方案。

本文展示了JavaScript中获取数组最后一个元素的五种具体代码示例,并借助console.time和console.timeEnd工具对JavaScript脚本程序的执行效率进行量化对比分析。

获取数组最后一个元素的方法

const arrayTest = [11, 22, 33];//示例数组

方法一:利用length属性

let lastValue0 = arrayTest[arrayTest.length - 1];
console.log(lastValue0);

方法二:使用数组slice方法

该方法返回一个仅包含最后一个元素的新数组。

let lastValue1 = arrayTest.slice(-1);
console.log(lastValue1[0]);

方法三:使用数组pop方法

pop()函数用于删除并返回数组的最后一个元素,注意此操作会直接修改原数组。

let lastValue2 = arrayTest.pop();
console.log(lastValue2);

方法四:使用数组at方法(ES2022新特性)

at()函数用于接收一个整数值并返回对应索引的元素,支持正数和负数索引。当使用负整数时,计数从数组的最后一个元素开始向前倒数。

let lastValue3 = arrayTest.at(-1);
console.log(lastValue3);

方法五:使用数组reverse()方法

reverse()函数可用于颠倒数组中元素的顺序,原本位于最前面的元素会变为最后面的元素。

let lastValue4 = arrayTest.reverse()[0];
console.log(lastValue4);

效率测试环节

具体测试代码如下所示:

const arrayTest = [11, 22, 33];
console.time("===> length");
let lastValue0 = arrayTest[arrayTest.length - 1];
console.log(lastValue0);
console.timeEnd("===> length");
// ===> length: 0.120849609375 ms
console.log(arrayTest);
console.time("===> slice");
let lastValue1 = arrayTest.slice(-1);
console.log(lastValue1[0]);
console.timeEnd("===> slice");
// ===> slice: 0.053955078125 ms
console.log(arrayTest);
console.time("===> pop");
let lastValue2 = arrayTest.pop();
console.log(lastValue2);
console.timeEnd("===> pop");
// ===> pop: 0.048095703125 ms
console.log(arrayTest);
arrayTest.push(33);
console.time("===> atat");
let lastValue3 = arrayTest.at(-1);
console.log(lastValue3);
console.timeEnd("===> atat");
// ===> atat: 0.0439453125 ms
console.log(arrayTest);
console.time("===> reverse");
let lastValue4 = arrayTest.reverse()[0];
console.log(lastValue4);
console.timeEnd("===> reverse");
// ===> reverse: 0.072998046875 ms
console.log(arrayTest); 

测试结果数据显示,at()方法的速度最快,整体效率最高。

至此,关于JavaScript获取数组最后一个元素的五种方法及其执行效率对比的介绍已结束。如需了解更多相关JS获取数组元素的方法,欢迎查阅本站历史文章或继续浏览后续内容,感谢大家的支持!

作者最新文章