if (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
EDIT - ES-2022
Using ES-2022 Array.at(), the above may be written like this:
if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
Answer from Aaron Butacov on Stack Overflowif (loc_array[loc_array.length - 1] === 'index.html') {
// do something
} else {
// something else
}
In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().
Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.
EDIT - ES-2022
Using ES-2022 Array.at(), the above may be written like this:
if (loc_array.at(-1) === 'index.html') {
// do something
} else {
// something else
}
Reference The slice() method of Array instances returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.
arr.slice(-1)[0]
or
arr.slice(-1).pop()
Both will return undefined if the array is empty.
javascript - Access last element of a TypeScript array - Stack Overflow
how to get the last element of an array?
The easy way to access the last JavaScript array element
How to get the last item of an array with destructuring
Why not just do array[array.lemth -1]
More on reddit.comVideos
You can access the array elements by its index. The index for the last element in the array will be the length of the array-1 (as indexes are zero based).
This should work:
var items: String[] = ["tom", "jeff", "sam"];
alert(items[items.length-1])
Here is a working sample.
As of July 2021, browsers are starting to support the at() method for Arrays which allows for the following syntax:
const arr: number[] = [1, 2, 3];
// shows 3
alert(arr.at(-1));
It's not clear to me at what point TypeScript will start to support this (it's not working for me just yet) but it should be available soon I would guess.
Edit: This is available as of [email protected]