Here is my JavaScript code so far:
var linkElement = document.getElementById(\"BackButton\");
var loc_array = document.location.href.split(\'/\');
var newT =
I'd rather use array.pop()
than indexes.
while(loc_array.pop()!= "index.html"){
}
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length])));
this way you always get the element previous to index.html (providing your array has isolated index.html as one item). Note: You'll lose the last elements from the array, though.
EDITED:
Recently I came up with one more solution which I now think is the best for my needs:
function w(anArray) {
return {
last() {
return anArray [anArray.length - 1];
};
};
}
With the above definition in effect I can now say:
let last = w ([1,2,3]).last();
console.log(last) ; // -> 3
The name "w" stands for "wrapper". You can see how you could easily add more methods besides 'last()' to this wrapper.
I say "best for my needs", because this allows me to easily add other such "helper methods" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.
The "cleanest" ES6 way (IMO) would be:
const foo = [1,2,3,4];
const bar = [...foo].pop();
This avoids mutating foo
, as .pop()
would had, if we didn't used the spread operator.
That said, I like aswell the foo.slice(-1)[0]
solution.
Multiple ways to find last value of an array in javascript
var arr = [1,2,3,4,5];
console.log(arr.slice(-1)[0])
console.log(arr[arr.length-1])
const [last] = [...arr].reverse();
console.log(last)
let copyArr = [...arr];
console.log(copyArr.reverse()[0]);
var arr = [1,2,3,4,5];
console.log(arr.pop())
arr.push(5)
console.log(...arr.splice(-1));
let arr = [1, 2, 3, 4, 5];
Object.defineProperty(arr, 'last',
{ get: function(){
return this[this.length-1];
}
})
console.log(arr.last);
To prevent removing last item from origin array you could use
Array.from(myArray).pop()
Mostly supported of all browsers (ES6)
reverse()
!!!A few answers mention reverse
but don't mention the fact that reverse
modifies the original array, and doesn't (as in some other language or frameworks) return a copy.
var animals = ['dog', 'cat'];
animals.reverse()[0]
"cat"
animals.reverse()[0]
"dog"
animals.reverse()[1]
"dog"
animals.reverse()[1]
"cat"
This can be the worst type of code to debug!