Get the last item in an array

前端 未结 30 2717
执念已碎
执念已碎 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:40

    jQuery solves this neatly:

    > $([1,2,3]).get(-1)
    3
    > $([]).get(-1)
    undefined
    
    0 讨论(0)
  • 2020-11-22 05:41
    const lastElement = myArray[myArray.length - 1];
    

    This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).

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

    Performance

    Today 2020.05.16 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6

    Conclusions

    • arr[arr.length-1] (D) is recommended as fastest cross-browser solution
    • mutable solution arr.pop() (A) and immutable _.last(arr) (L) are fast
    • solutions I, J are slow for long strings
    • solutions H, K (jQuery) are slowest on all browsers

    Details

    I test two cases for solutions:

    • mutable: A, B, C,

    • immutable: D, E, F, G, H, I, J (my),

    • immutable from external libraries: K, L, M,

    for two cases

    • short string - 10 characters - you can run test HERE
    • long string - 1M characters - you can run test HERE

    function A(arr) {
      return arr.pop();
    }
    
    function B(arr) {  
      return arr.splice(-1,1);
    }
    
    function C(arr) {  
      return arr.reverse()[0]
    }
    
    function D(arr) {
      return arr[arr.length - 1];
    }
    
    function E(arr) {
      return arr.slice(-1)[0] ;
    }
    
    function F(arr) {
      let [last] = arr.slice(-1);
      return last;
    }
    
    function G(arr) {
      return arr.slice(-1).pop();
    }
    
    function H(arr) {
      return [...arr].pop();
    }
    
    function I(arr) {  
      return arr.reduceRight(a => a);
    }
    
    function J(arr) {  
      return arr.find((e,i,a)=> a.length==i+1);
    }
    
    function K(arr) {  
      return $(arr).get(-1);
    }
    
    function L(arr) {  
      return _.last(arr);
    }
    
    function M(arr) {  
      return _.nth(arr, -1);
    }
    
    
    
    
    
    
    // ----------
    // TEST
    // ----------
    
    let loc_array=["domain","a","b","c","d","e","f","g","h","file"];
    
    log = (f)=> console.log(`${f.name}: ${f([...loc_array])}`);
    
    [A,B,C,D,E,F,G,H,I,J,K,L,M].forEach(f=> log(f));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>

    Example results for Chrome for short string

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

    ES6 object destructuring is another way to go.

    const {length, [length-1]: last}=[1,2,3,4,5]
    console.log(last)

    You extract length property from Array using object destructuring. You create another dynamic key using already extracted key by [length-1] and assign it to last, all in one line.

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

    Two options are:

    var last = arr[arr.length - 1]
    

    or

    var last = arr.slice(-1)[0]
    

    The former is faster, but the latter looks nicer

    http://jsperf.com/slice-vs-length-1-arr

    0 讨论(0)
  • 2020-11-22 05:46
    if (loc_array[loc_array.length - 1] === 'index.html') {
       // do something
    } else {
       // something else
    }
    

    In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().

    Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.

    0 讨论(0)
提交回复
热议问题