Get the last item in an array

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

    Not sure if there's a drawback, but this seems quite concise:

    arr.slice(-1)[0] 
    

    or

    arr.slice(-1).pop()
    

    Both will return undefined if the array is empty.

    0 讨论(0)
  • 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 
    
    0 讨论(0)
  • 2020-11-22 05:53

    const [lastItem] = array.slice(-1);

    Array.prototype.slice with -1 can be used to create a new Array containing only the last item of the original Array, you can then use Destructuring Assignment to create a variable using the first item of that new Array.

    const lotteryNumbers = [12, 16, 4, 33, 41, 22];
    const [lastNumber] = lotteryNumbers.slice(-1);
    
    console.log(lotteryNumbers.slice(-1));
    // => [22]
    console.log(lastNumber);
    // => 22

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

    Getting the last item of an array can be achieved by using the slice method with negative values.

    You can read more about it here at the bottom.

    var fileName = loc_array.slice(-1)[0];
    if(fileName.toLowerCase() == "index.html")
    {
      //your code...
    }
    

    Using pop() will change your array, which is not always a good idea.

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

    You can use this pattern...

    let [last] = arr.slice(-1);
    

    While it reads rather nicely, keep in mind it creates a new array so it's less efficient than other solutions but it'll almost never be the performance bottleneck of your application.

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

    In ECMAScript proposal Stage 1 there is a suggestion to add an array property that will return the last element: proposal-array-last.

    Syntax:

    arr.lastItem // get last item
    arr.lastItem = 'value' // set last item
    
    arr.lastIndex // get last index
    

    You can use polyfill.

    Proposal author: Keith Cirkel(chai autor)

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