jQuery equivalent to Prototype array.last()

Viewed 143647

Prototype:

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

Anything similar to this in jQuery?

13 Answers

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

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.

You can use this Arr.slice(-1)[0].

Arr=[1,2,3,4,5,6,7]

Lets understand this. -1 means you are looking last index of Array. so when you use Arr.slice(-1)[0] then you will get result : 7.

Related