Home >Web Front-end >JS Tutorial >How to Get and Check the Last Item in a JavaScript Array?
Get the Last Item in an Array with JavaScript
This JavaScript code retrieves the second to last item from a URL array:
var loc_array = document.location.href.split('/'); var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); linkElement.appendChild(newT);
However, to get the last item in the array and check if it's "index.html," use the following JavaScript:
if (loc_array[loc_array.length - 1] === 'index.html') { // Perform an action } else { // Perform a different action }
To handle case-insensitive checks, use .toLowerCase():
if (loc_array[loc_array.length - 1].toLowerCase() === 'index.html') { // Perform an action } else { // Perform a different action }
Consider performing this check server-side for improved performance and compatibility for users without JavaScript.
ES2022 Array.at() Method
In ES2022, you can use the Array.at() method to simplify the code:
if (loc_array.at(-1) === 'index.html') { // Perform an action } else { // Perform a different action }
The above is the detailed content of How to Get and Check the Last Item in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!