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.
To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.
The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr[3].
Use the array. prototype. splice() to Remove the Last Element From an Array JavaScript. The splice() method is used to change the array by removing or replacing the elements.
Why not just use simple javascript?
var array=[1,2,3,4];
var lastEl = array[array.length-1];
You can write it as a method too, if you like (assuming prototype has not been included on your page):
Array.prototype.last = function() {return this[this.length-1];}
with slice():
var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]
with pop();
var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]
see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information
When dealing with a jQuery object, .last()
will do just that, filter the matched elements to only the last one in the set.
Of course, you can wrap a native array with jQuery leading to this:
var a = [1,2,3,4];
var lastEl = $(a).last()[0];
Why not use the get function?
var a = [1,2,3,4];
var last = $(a).get(-1);
http://api.jquery.com/get/ More info
Edit: As pointed out by DelightedD0D, this isn't the correct function to use as per jQuery's docs but it does still provide the correct results. I recommend using Salty's answer to keep your code correct.
For arrays, you could simply retrieve the last element position with array.length - 1
:
var a = [1,2,3,4];
var lastEl = a[a.length-1]; // 4
In jQuery you have the :last selector, but this won't help you on plain arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With