문제

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.

 

예제

nums.last() 호출 시 마지막 원소인 3을 반환해야 한다.

 

배열 내에 원소가 없을 경우, -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
 */

현재 배열의 길이가 0인 경우, 즉 배열 내에 원소가 없는 경우 -1을 반환한다. 그렇지 않다면 length 메소드를 이용하여 배열의 마지막 원소를 반환한다.

'Algorithm' 카테고리의 다른 글

[LeetCode] 2634. Filter Elements from Array  (0) 2024.01.22
[LeetCode] 2629. Function Composition  (0) 2024.01.21
[LeetCode] 2626. Array Reduce Transformation  (0) 2024.01.21
[LeetCode] 2621. Sleep  (0) 2024.01.19
[LeetCode] 2620. Counter  (0) 2024.01.19

+ Recent posts