js獲取數組最后一位元素的五種方法及執(zhí)行效率對比
更新時間:2023年08月06日 15:10:19 投稿:yin
js獲取數組最后一位元素的五種方法代碼示例,使用console.time和console.timeEnd測量javascript腳本程序執(zhí)行效率對比
js獲取數組最后一位元素的五種方法代碼示例,使用console.time和console.timeEnd測量javascript腳本程序執(zhí)行效率對比。
數組最后一位元素的獲取方法
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() 方法速度最快,效率最高。
到此這篇關于js獲取數組最后一位元素的五種方法及執(zhí)行效率對比的文章就介紹到這了,更多相關js獲取數組最后一位元素的方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
深入理解JavaScript中為什么string可以擁有方法
下面小編就為大家?guī)硪黄钊肜斫釰avaScript中為什么string可以擁有方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05