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.
A shorter version of what @chaiguy posted:
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.
Two options are:
or
The former is faster, but the latter looks nicer
http://jsperf.com/slice-vs-length-1-arr
You can add a
last()
function to theArray
prototype.The simple way to get last item of array:
Of course, we need to check to make sure array has at least one item first.
For those not afraid to overload the Array prototype (and with enumeration masking you shouldn't be):
You could add a new property getter to the prototype of
Array
so that it is accessible through all instances ofArray
.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 stillundefined
(not defined by another script that might rely on it).Does not work in IE ≤ 8.