js獲取數(shù)組最后一位元素的五種方法及執(zhí)行效率對比
js獲取數(shù)組最后一位元素的五種方法代碼示例,使用console.time和console.timeEnd測量javascript腳本程序執(zhí)行效率對比。
數(shù)組最后一位元素的獲取方法
const arrayTest = [11, 22, 33];//示例數(shù)組
一、 利用length
let lastValue0 = arrayTest[arrayTest.length - 1]; console.log(lastValue0);
二、 數(shù)組slice方法
返回值為包含最后一位元素的新數(shù)組
let lastValue1 = arrayTest.slice(-1); console.log(lastValue1[0]);
三、 數(shù)組pop方法
pop() 方法用于刪除并返回數(shù)組的最后一個元素 (會修改原數(shù)組)
let lastValue2 = arrayTest.pop(); console.log(lastValue2);
四、 數(shù)組at方法(ES2022新特性)
at() 方法用于接收一個整數(shù)值并返回該索引對應(yīng)的元素,允許正數(shù)和負數(shù)。負整數(shù)從數(shù)組中的最后一個元素開始倒數(shù)。
let lastValue3 = arrayTest.at(-1); console.log(lastValue3);
五、數(shù)組 reverse()方法
reverse()可以用于顛倒數(shù)組中元素的順序,最前面的元素會變成最后面的元素。
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); 測試結(jié)果表示,at() 方法速度最快,效率最高。
到此這篇關(guān)于js獲取數(shù)組最后一位元素的五種方法及執(zhí)行效率對比的文章就介紹到這了,更多相關(guān)js獲取數(shù)組最后一位元素的方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解JavaScript中為什么string可以擁有方法
下面小編就為大家?guī)硪黄钊肜斫釰avaScript中為什么string可以擁有方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05
小程序卡片切換效果組件wxCardSwiper的實現(xiàn)
這篇文章主要介紹了小程序卡片切換效果組件wxCardSwiper的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
基于JavaScript實現(xiàn)圖片連播和聯(lián)級菜單實例代碼
這篇文章主要介紹了基于JavaScript實現(xiàn)圖片連播和聯(lián)級菜單實例代碼,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-07-07
TypeScript裝飾器與反射元數(shù)據(jù)實例詳解
TypeScript的裝飾器為我們提供了一種強大的工具,可以在運行時改變類的行為,通過理解裝飾器的工作原理,我們可以創(chuàng)造更加強大、靈活且易于維護的應(yīng)用,這篇文章主要介紹了TypeScript裝飾器與反射元數(shù)據(jù),需要的朋友可以參考下2023-09-09

