Get the last item in an array

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

提交回复
热议问题