Get the last item in an array

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

    Here's how to get it with no effect on the original ARRAY

    a = [1,2,5,6,1,874,98,"abc"];
    a.length; //returns 8 elements
    

    If you use pop(), it will modify your array

    a.pop();  // will return "abc" AND REMOVES IT from the array 
    a.length; // returns 7
    

    But you can use this so it has no effect on the original array:

    a.slice(-1).pop(); // will return "abc" won't do modify the array 
                       // because slice creates a new array object 
    a.length;          // returns 8; no modification and you've got you last element 
    

提交回复
热议问题