Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.You may assume the array is the output of JSON.parse. Example 1:Input: nums = [null, {}, 3]Output: 3Explanation: Calling nums.last() should return the last element: 3.Example 2:Input: nums = []Output: -1Explanation: Because there are no elements, return -1. Constraints:arr is a valid JSON array0 <= arr.length <= 1000
Question
Write code that enhances all arrays such that you can call the array.last() method on any array and it will return the last element. If there are no elements in the array, it should return -1.You may assume the array is the output of JSON.parse. Example 1:Input: nums = [null, {}, 3]Output: 3Explanation: Calling nums.last() should return the last element: 3.Example 2:Input: nums = []Output: -1Explanation: Because there are no elements, return -1. Constraints:arr is a valid JSON array0 <= arr.length <= 1000
Solution
The problem is asking to add a method to the Array prototype in JavaScript. This method, called last, should return the last element of the array if it exists, or -1 if the array is empty. Here is how you can do it:
Array.prototype.last = function() {
if (this.length === 0) {
return -1;
} else {
return this[this.length - 1];
}
};
In this code, Array.prototype.last adds a new method to all arrays. this refers to the array on which the method is called. If the array is empty (this.length === 0), the method returns -1. Otherwise, it returns the last element of the array (this[this.length - 1]).
Similar Questions
How do you remove the last element from an array in JavaScript?A. arr.pop()B. arr.delete()C. arr.remove()D. arr.splice()
1Which of the following methods is used to return the last element of an array?Review Laterpop()slice()splice()reduce()
Which of the following methods is used to remove the last element from an array in JavaScript?Optionsunshift()shift()pop()splice()
Which of the following methods is used to remove the last element from an array in JavaScript?Optionspop()shift()splice()unshift()
Let list1 =[1,2,3,4,5,6]. How to access the last element?list1[-1]list1[5]BothNone
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.