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.
There is also a npm module, that add
last
toArray.prototype
usage
This is the best options from performance point of view (~1000 times faster than arr.slice(-1)).
If one wants to get the last element in one go, he/she may use
Array#splice()
:Here, there is no need to store the split elements in an array, and then get to the last element. If getting last element is the only objective, this should be used.
Note: This changes the original array by removing its last element. Think of
splice(-1,1)
as apop()
function that pops the last element.jQuery solves this neatly:
This question has been around a long time, so I'm surprised that no one mentioned just putting the last element back on after a
pop()
.arr.pop()
is exactly as efficient asarr[arr.length-1]
, and both are the same speed asarr.push()
.Therefore, you can get away with:
Which can be reduced to this (same speed):
This is twice as slow as
arr[arr.length-1]
, but you don't have to stuff around with an index. That's worth gold on any day.Of the solutions I've tried, and in multiples of the Execution Time Unit (ETU) of
arr[arr.length-1]
:[Method]..............[ETUs 5 elems]...[ETU 1 million elems]
The last three options, ESPECIALLY
[...arr].pop()
, get VERY much worse as the size of the array increases. On a machine without the memory limitations of my machine,[...arr].pop()
probably maintains something like it's 120:1 ratio. Still, no one likes a resource hog.I generally use underscorejs, with it you can just do
For me that is more semantic than
loc_array.slice(-1)[0]