最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js獲取數(shù)組最后一位元素的五種方法及執(zhí)行效率對比

 更新時(shí)間:2023年08月06日 15:10:19   投稿:yin  
js獲取數(shù)組最后一位元素的五種方法代碼示例,使用console.time和console.timeEnd測量javascript腳本程序執(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() 方法用于刪除并返回?cái)?shù)組的最后一個(gè)元素 (會(huì)修改原數(shù)組)

let lastValue2 = arrayTest.pop();
console.log(lastValue2);

四、 數(shù)組at方法(ES2022新特性)

at() 方法用于接收一個(gè)整數(shù)值并返回該索引對應(yīng)的元素,允許正數(shù)和負(fù)數(shù)。負(fù)整數(shù)從數(shù)組中的最后一個(gè)元素開始倒數(shù)。

let lastValue3 = arrayTest.at(-1);
console.log(lastValue3);

五、數(shù)組 reverse()方法

reverse()可以用于顛倒數(shù)組中元素的順序,最前面的元素會(huì)變成最后面的元素。

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)文章

最新評論

湘阴县| 疏附县| 禹城市| 丰镇市| 武夷山市| 南昌县| 马关县| 怀来县| 明溪县| 乃东县| 吕梁市| 许昌市| 修武县| 曲阳县| 轮台县| 五指山市| 中江县| 赣榆县| 玉屏| 于田县| 江孜县| 濮阳市| 阿克陶县| 武强县| 璧山县| 普宁市| 阿城市| 桓仁| 和平区| 信阳市| 郁南县| 永清县| 兰考县| 雷州市| 阿拉尔市| 靖安县| 石阡县| 彰化市| 沂南县| 驻马店市| 德令哈市|