亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript獲取數(shù)組最后一個元素的3種方法以及性能

 更新時間:2023年06月12日 15:11:43   作者:Web_boom  
在開發(fā)過程中,我們常常需要得到js數(shù)組的最后一個數(shù)組元素,下面這篇文章主要給大家介紹了關于JavaScript獲取數(shù)組最后一個元素的3種方法以及性能,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

前言

當需要從 JavaScript 中的數(shù)組中獲取最后一個元素時,有多種選擇,本文將提供 3 種可用方法。

1. 數(shù)組 length 屬性

length 屬性返回數(shù)組中元素的數(shù)量。從數(shù)組的長度中減去 1 得到數(shù)組最后一個元素的索引,使用它可以訪問最后一個元素。從長度中減去 1 的原因是,在 JavaScript 中,數(shù)組索引編號從 0 開始。即第一個元素的索引將為 0。因此,最后一個元素的索引將為數(shù)組的 length-1。

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

2. 數(shù)組 slice 方法

slice() 方法從一個數(shù)組中返回特定的元素,作為一個新的數(shù)組對象。此方法選擇從給定開始索引開始到給定結(jié)束索引結(jié)束的元素,不包括結(jié)束索引處的元素。slice() 方法不會修改現(xiàn)有數(shù)組,提供一個索引值返回該位置的元素,負索引值從數(shù)組末尾計算索引。數(shù)組匹配的解構(gòu)賦值用于從 slice() 方法返回的數(shù)組中獲取元素。

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

3. 數(shù)組 pop 方法

pop() 方法從數(shù)組中刪除最后一個元素并將其返回,此方法會修改原來的數(shù)組。如果數(shù)組為空,則返回 undefined 并且不修改數(shù)組。

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"); 

輸出的結(jié)果如下:

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

總結(jié)

pop() 方法是最快的,如果可以修改數(shù)組,則可以使用它。如果你不想改變數(shù)組,可以使用 slice() 方法。利用數(shù)組 length 屬性的方法是最慢的,屬于是獲取數(shù)組最后一個元素的最常用方法。

到此這篇關于JavaScript獲取數(shù)組最后一個元素的3種方法以及性能的文章就介紹到這了,更多相關JS獲取數(shù)組最后一個元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論