Get the last item in an array

前端 未结 30 2719
执念已碎
执念已碎 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 05:55

    Just putting another option here.

    loc_array.splice(-1)[0] === 'index.html'
    

    I found the above approach more clean and short onliner. Please, free feel to try this one.

    Note: It will modify the original array, if you don't want to modify it you can use slice()

    loc_array.slice(-1)[0] === 'index.html'
    

    Thanks @VinayPai for pointing this out.

    0 讨论(0)
  • 2020-11-22 05:57

    Personally I would upvote answer by kuporific / kritzikratzi. The array[array.length-1] method gets very ugly if you're working with nested arrays.

    var array = [[1,2,3], [4,5,6], [7,8,9]]
    ​
    array.slice(-1)[0]
    ​
    //instead of 
    ​
    array[array.length-1]
    ​
    //Much easier to read with nested arrays
    ​
    array.slice(-1)[0].slice(-1)[0]
    ​
    //instead of
    ​
    array[array.length-1][array[array.length-1].length-1]
    
    0 讨论(0)
  • 2020-11-22 05:59

    Here's more Javascript art if you came here looking for it

    In the spirit of another answer that used reduceRight(), but shorter:

    [3, 2, 1, 5].reduceRight(a => a);
    

    It relies on the fact that, in case you don't provide an initial value, the very last element is selected as the initial one (check the docs here). Since the callback just keeps returning the initial value, the last element will be the one being returned in the end.

    Beware that this should be considered Javascript art and is by no means the way I would recommend doing it, mostly because it runs in O(n) time, but also because it hurts readability.

    And now for the serious answer

    The best way I see (considering you want it more concise than array[array.length - 1]) is this:

    const last = a => a[a.length - 1];
    

    Then just use the function:

    last([3, 2, 1, 5])
    

    The function is actually useful in case you're dealing with an anonymous array like [3, 2, 1, 5] used above, otherwise you'd have to instantiate it twice, which would be inefficient and ugly:

    [3, 2, 1, 5][[3, 2, 1, 5].length - 1]
    

    Ugh.

    For instance, here's a situation where you have an anonymous array and you'd have to define a variable, but you can use last() instead:

    last("1.2.3".split("."));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 06:00

    If one wants to get the last element in one go, he/she may use Array#splice():

    lastElement = document.location.href.split('/').splice(-1,1);
    

    Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.

    Note: This changes the original array by removing its last element. Think of splice(-1,1) as a pop() function that pops the last element.

    0 讨论(0)
  • 2020-11-22 06:00

    For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):

    Object.defineProperty( Array.prototype, "getLast", {
        enumerable: false,
        configurable: false,
        writable: false,
        value: function() {
            return this[ this.length - 1 ];
        }
    } );
    
    0 讨论(0)
提交回复
热议问题