JavaScript 中獲取數組最后一個元素3種方法及性能

當需要從 JavaScript 中的數組中獲取最后一個元素時,有多種選擇,本文將提供 3 種可用方法。
關于數組操作的方法,可以查閱以下文章:
- JavaScript 數組操作必須熟練運用的10個方法
- JavaScript 數組方法 slice() 的 5 個示例
- JavaScript 數組展平方法: flat() 和 flatMap()
- JavaScript 數組方法 .map() 的 5 個使用場景
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 屬性的方法是最慢的,屬于是獲取數組最后一個元素的最常用方法。