Get the last item in an array

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

    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.

提交回复
热议问题