Get the last item in an array

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

    You could add a new property getter to the prototype of Array so that it is accessible through all instances of Array.

    Getters allow you to access the return value of a function just as if it were the value of a property. The return value of the function of course is the last value of the array (this[this.length - 1]).

    Finally you wrap it in a condition that checks whether the last-property is still undefined (not defined by another script that might rely on it).

    if(typeof Array.prototype.last === 'undefined') {
        Object.defineProperty(Array.prototype, 'last', {
            get : function() {
                return this[this.length - 1];
            }
        });
    }
    
    // Now you can access it like
    [1, 2, 3].last;            // => 3
    // or
    var test = [50, 1000];
    alert(test.last);          // Says '1000'
    

    Does not work in IE ≤ 8.

    0 讨论(0)
  • 2020-11-22 06:01

    I generally use underscorejs, with it you can just do

    if (_.last(loc_array) === 'index.html'){
      etc...
    }
    

    For me that is more semantic than loc_array.slice(-1)[0]

    0 讨论(0)
  • 2020-11-22 06:02

    You can add a last() function to the Array prototype.

    Array.prototype.last = function () {
        return this[this.length - 1];
    };
    
    0 讨论(0)
  • 2020-11-22 06:05

    Not implemented yet!

    The new TC39 Array.prototype.lastItem proposal (stage 1) adds a getter that returns the last item in an array:

    const myArray = [1, 2, 3]
    
    console.log(myArray.lastItem)
    //=> 3
    

    The Array.prototype.item proposal (stage 3) adds a different API:

    const myArray = [1, 2, 3]
    
    console.log(myArray.item(-1))
    //=> 3
    
    0 讨论(0)
  • 2020-11-22 06:06

    Use Array.pop:

    var lastItem = anArray.pop();
    

    Important : This returns the last element and removes it from the array

    0 讨论(0)
  • 2020-11-22 06:06

    A shorter version of what @chaiguy posted:

    Array.prototype.last = function() {
        return this[this.length - 1];
    }
    

    Reading the -1 index returns undefined already.

    EDIT:

    These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.

    export function last(array) {
        return array[array.length - 1];
    }
    
    0 讨论(0)
提交回复
热议问题