Get the last item in an array

2018-12-31 14:16发布

Here is my JavaScript code so far:

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.

30条回答
浮光初槿花落
2楼-- · 2018-12-31 14:41

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];
}
查看更多
美炸的是我
3楼-- · 2018-12-31 14:41

Two options are:

var last = arr[arr.length - 1]

or

var last = arr.slice(-1)[0]

The former is faster, but the latter looks nicer

http://jsperf.com/slice-vs-length-1-arr

查看更多
人间绝色
4楼-- · 2018-12-31 14:41

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

Array.prototype.last = function () {
    return this[this.length - 1];
};
查看更多
有味是清欢
5楼-- · 2018-12-31 14:41

The simple way to get last item of array:

var last_item = loc_array.reverse()[0];

Of course, we need to check to make sure array has at least one item first.

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 14:42

For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):

Object.defineProperty( Array.prototype, "getLast", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function() {
        return this[ this.length - 1 ];
    }
} );
查看更多
栀子花@的思念
7楼-- · 2018-12-31 14:42

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.

查看更多
登录 后发表回答