Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last item of array without pop? [duplicate]

Tags:

I need the same result as:

var array = [1, 2, 3, 5, 7]; var top = array.pop(); 

The problem is that pop removes the element from the array. To fix that I added another line:

array.push(top); 

But it is annoying me, I did it four or five times in this project till now. Is there a better way?

like image 505
Washington Guedes Avatar asked Jun 30 '16 15:06

Washington Guedes


1 Answers

When grabbing from the end you can do array[array.length - x], where x is the number of items from the end you wanna grab.

For instance, to grab the last item you would use array[array.length - 1].

like image 176
Michael Jones Avatar answered Oct 08 '22 13:10

Michael Jones