Home > Web Front-end > JS Tutorial > How to Get and Check the Last Item in a JavaScript Array?

How to Get and Check the Last Item in a JavaScript Array?

Barbara Streisand
Release: 2024-12-07 06:17:12
Original
752 people have browsed it

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);
Copy after login

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
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template