Source
https://leetcode.com/problems/array-prototype-last/
Code
Array.prototype.last = function () {
if (this.length) {
return this[this.length - 1];
} else {
return -1;
}
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
How to solve?
리트코드에 자바스크립트 문제가 새로 생겨서 풀어봤다.
this 바인딩을 이용해서 프로토타입의 메서드를 만들어준다.
코드 분석 소스
Array.prototype.last = function() {
return this[this.length - 1] ?? -1;
};
Nullish 병합 연산자를 사용해서 문제를 해결할 수 있다.
'Problem solve' 카테고리의 다른 글
[LeetCode] 35. Search Insert Position (Javascript) (0) | 2023.04.24 |
---|---|
[Leetcode] 14. Longest Common Prefix (0) | 2023.04.18 |
[Leetcode] 13. Roman to Integer (Javascript) (0) | 2023.04.11 |
[Leetcode] 66. Plus One (Javascript) (0) | 2023.04.10 |
[Leetcode] 46. Permutation (Javascript) (0) | 2023.04.09 |