Getting the last item in the array
By xyz on 2 weeks ago|0 comment||
0
Array.prototype.slice(begin, end) is used to cut arrays when you set the start and end arguments. But if you don't set the end argument, this function will automatically set the max value for the array.
A smart hack is it can also accept negative values and by setting a negative number as begin argument, you will get the last elements from the array.
var array = [1, 2, 3, 4, 5, 6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]
Add a Comment
Comments
Comments MIA, jokes needed ASAP. Add yours! 😄