Problem
Description
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.
Constraints:
arris a valid JSON array0 <= arr.length <= 1000
Starter
/**
* @return {null|boolean|number|string|Array|Object}
*/
Array.prototype.last = function() {
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
Solution
1. Array.prototype.last = function() { … } 這段是幫所有陣列新增一個方法。
- 在
Array.prototype上新增了一個名為last的方法。 - 因為所有陣列都會沿著原型鏈找方法,所以之後所有陣列都能呼叫
last()。
2. arr.at() 是 ES2022 新增的陣列方法,用來透過索引取得元素。
特點:
- 支援正數索引(從前面數)。
- 支援負數索引(從後面數,
-1= 最後一個元素)。 - 不會修改原陣列。
- 如果索引超出範圍,回傳
undefined。
語法:
arr.at(index)
index:要取的元素索引,支援負數。
基本範例:
const arr = [10, 20, 30, 40, 50];
// 正數索引
console.log(arr.at(0)); // 10
console.log(arr.at(2)); // 30
// 負數索引
console.log(arr.at(-1)); // 50 最後一個
console.log(arr.at(-2)); // 40 倒數第二個
// 超出範圍
console.log(arr.at(10)); // undefined
console.log(arr.at(-10)); // undefined
與傳統索引對比:
console.log(arr[arr.length - 1]); // 50
console.log(arr.at(-1)); // 50
差異:
.at(-1)語意更明確,可直接取「最後一個元素」。傳統方式arr[arr.length - 1]可用於所有 JS 環境,但不直覺,特別是倒數第 N 個元素時。
空陣列與邊界:
const empty = [];
console.log(empty.at(0)); // undefined
console.log(empty.at(-1)); // undefined
- 不會 throw error,只回傳
undefined。
Code
/**
* @return {null|boolean|number|string|Array|Object}
*/
Array.prototype.last = function() {
return this.length === 0 ? -1 : this.at(-1);
};
/**
* const arr = [1, 2, 3];
* arr.last(); // 3
*/
喜歡我的文章,拍五下~





