Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last item in an array

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.

like image 949
balexander Avatar asked Jul 09 '10 19:07

balexander


People also ask

How do I find the last value in an array?

1) Using the array length property The length property returns the number of elements in an array. Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed.

What is the last element of array in C?

The last element of an array is at position size - 1.

How do you find the last and first of an array?

To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.

How do you find the last value of an object?

You can access the last value in an object directly, by using the Object. values() method to get an array of the object's values and calling the pop() method on the result, e.g. Object. values(obj). pop() .


1 Answers

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.

like image 182
Aaron Harun Avatar answered Sep 20 '22 00:09

Aaron Harun