jQuery equivalent to Prototype array.last()
Prototype:
var array = [1,2,3,4];
var lastEl = array.last();
Anything similar to this in jQuery?
Solution 1:
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];}
Solution 2:
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
Solution 3:
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];
Solution 4:
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.
Solution 5:
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.