JavaScript 中获取数组最后一个元素3种方法及性能

JavaScript 中获取数组最后一个元素3种方法及性能

当需要从 JavaScript 中的数组中获取最后一个元素时,有多种选择,本文将提供 3 种可用方法。

关于数组操作的方法,可以查阅以下文章:

1. 数组 length 属性

length 属性返回数组中元素的数量。从数组的长度中减去 1 得到数组最后一个元素的索引,使用它可以访问最后一个元素。从长度中减去 1 的原因是,在 JavaScript 中,数组索引编号从 0 开始。即第一个元素的索引将为 0。因此,最后一个元素的索引将为数组的 length-1

const arrayTest = ["第一个元素", "第二个元素", "最后一个元素"];
const length = arrayTest.length;
const lastValue = arrayTest[length - 1];
console.log(lastValue); // 最后一个元素

2. 数组 slice 方法

slice() 方法从一个数组中返回特定的元素,作为一个新的数组对象。此方法选择从给定开始索引开始到给定结束索引结束的元素,不包括结束索引处的元素。slice() 方法不会修改现有数组,提供一个索引值返回该位置的元素,负索引值从数组末尾计算索引。数组匹配的解构赋值用于从 slice() 方法返回的数组中获取元素。

const arrayTest = ["第一个元素", "第二个元素", "最后一个元素"];
const length = arrayTest.length;
const [lastValue] = arrayTest.slice(-1);
console.log(lastValue); // 最后一个元素

3. 数组 pop 方法

pop() 方法从数组中删除最后一个元素并将其返回,此方法会修改原来的数组。如果数组为空,则返回 undefined 并且不修改数组。

const arrayTest = ["第一个元素", "第二个元素", "最后一个元素"];
const length = arrayTest.length;
const lastValue = arrayTest.pop();
console.log(lastValue); // 最后一个元素
console.log(arrayTest); // [ '第一个元素', '第二个元素' ]

性能比较

让按性能比较这 3 种方法。

const arrayTest = ["第一个元素", "第二个元素", "最后一个元素"];

console.time("==> length");
const length = arrayTest.length;
let lastValue = arrayTest[length - 1];
console.log(lastValue);
console.timeEnd("==> length");

console.time("====> slice");
let [lastValue1] = arrayTest.slice(-1);
console.log(lastValue1);
console.timeEnd("====> slice");

console.time("======> pop");
let lastValue2 = arrayTest.pop();
console.log(lastValue2);
console.timeEnd("======> pop");

输出的结果如下:

最后一个元素
==> length: 6.38ms
最后一个元素
====> slice: 0.038ms
最后一个元素
======> pop: 0.033ms

总结

pop() 方法是最快的,如果可以修改数组,则可以使用它。如果你不想改变数组,可以使用 slice() 方法。利用数组 length 属性的方法是最慢的,属于是获取数组最后一个元素的最常用方法。