javascript tutorial - [Solved-5 Solutions] Get the last item in an array - javascript - java script - javascript array



Problem:

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);
click below button to copy the code. By JavaScript tutorial team

Currently it takes the second to last item in the array from the URL. However we 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.

Solution 1:

if(loc_array[loc_array.length-1] == 'index.html'){
 //do something
}else{
 //something else.
}
click below button to copy the code. By JavaScript tutorial team

In the event that our server serves the same file for "index.html" and "inDEX.htML" we can also use: .toLowerCase().

Solution 2:

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

arr.slice(-1)[0] 
or
arr.slice(-1).pop()
click below button to copy the code. By JavaScript tutorial team

Both will return undefined if the array is empty.

Solution 3:


var lastItem = anArray.pop();
click below button to copy the code. By JavaScript tutorial team

Solution 4:

A shorter version of what @chaiguy posted:

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

click below button to copy the code. By JavaScript tutorial team

Solution 5:

Two options are:

var last = arr[arr.length - 1]
or
var last = arr.slice(-1)[0]
click below button to copy the code. By JavaScript tutorial team

The former is faster, but the latter looks nicer


Related Searches to javascript tutorial - Get the last item in an array