코딩 테스트 풀이 🛠
[leetcode] 2619. Array Prototype Last
엄성준
2023. 11. 17. 23:23
728x90
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: 3
Explanation: Calling nums.last() should return the last element: 3.
Example 2:
Input: nums = []
Output: -1
Explanation: Because there are no elements, return -1.
나의 풀이
/**
* @return {null|boolean|number|string|Array|Object}
*/
Array.prototype.last = function() {
if(this.length === 0) return -1
return this[this.length-1]
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
처음에 인자에 대해서 어떻게 접근할까 고민을 하다가 다른 분이 풀어진 풀이의 코드를 참고하고 this 문법을 이용했습니다.
728x90