programming-examples/js/Array/Write a JavaScript function to get the last element of an array. Passing a parameter 'n' will return the last 'n' elements of the array..js

11 lines
323 B
JavaScript
Raw Normal View History

2019-11-15 12:59:38 +01:00
last = function(array, n) {
if (array == null)
return void 0;
if (n == null)
return array[array.length - 1];
return array.slice(Math.max(array.length - n, 0));
};
console.log(last([7, 9, 0, -2]));
console.log(last([7, 9, 0, -2],3));
console.log(last([7, 9, 0, -2],6));