views:

2445

answers:

4

Prototype:

var array = [1,2,3,4]; var lastEl = array.last();

Anything similar to this in jQuery?

+7  A: 

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];}
Salty
because something like the following will not look good:$('a').attr('href').split('#').last(); <-- of course last() is not a jquery function here... it's just to make an example
Looks good to me. Why do you say it doesn't? The call to .split() ends chain-ability so no loss there.
Ken Browning
I agree with Ken. Plus, does that look better than: $('a').attr('href').split('#')[$('a').attr('href').split('#').length-1], haha.
Salty
+1  A: 

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.

CMS
+1  A: 

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 http://www.w3schools.com/jsref/jsref_obj_array.asp for more information

guybrush
Why not just `.slice().pop()` copy the array and pop an element off the copy?
gnarf
+2  A: 

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];
gnarf