Get the last item in an array

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

提交回复
热议问题