Get the last item in an array

前端 未结 30 3305
执念已碎
执念已碎 2020-11-22 05:28

Here is my JavaScript code so far:

var linkElement = document.getElementById(\"BackButton\");
var loc_array = document.location.href.split(\'/\');
var newT =         


        
30条回答
  •  清歌不尽
    2020-11-22 06:00

    This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a pop().

    arr.pop() is exactly as efficient as arr[arr.length-1], and both are the same speed as arr.push().

    Therefore, you can get away with:

    ---EDITED [check that thePop isn't undefined before pushing]---

    let thePop = arr.pop()
    thePop && arr.push(thePop)
    

    ---END EDIT---

    Which can be reduced to this (same speed [EDIT: but unsafe!]):

    arr.push(thePop = arr.pop())    //Unsafe if arr empty
    

    This is twice as slow as arr[arr.length-1], but you don't have to stuff around with an index. That's worth gold on any day.

    Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of arr[arr.length-1]:

    [Method]..............[ETUs 5 elems]...[ETU 1 million elems]

    arr[arr.length - 1]      ------> 1              -----> 1
    
    let myPop = arr.pop()
    arr.push(myPop)          ------> 2              -----> 2
    
    arr.slice(-1).pop()      ------> 36             -----> 924  
    
    arr.slice(-1)[0]         ------> 36             -----> 924  
    
    [...arr].pop()           ------> 120            -----> ~21,000,000 :)
    

    The last three options, ESPECIALLY [...arr].pop(), get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine, [...arr].pop() probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.

提交回复
热议问题