[Easy] 實作 Array.prototype.at
2024年3月8日
重點摘要
本文介紹如何實作 Array.prototype.at 函式,此函式可用於從陣列中檢索指定索引的元素。本文也說明了如何處理各種情況,例如使用負整數索引等。
題目描述
請實作 Array.prototype.at,該方法會接受一個整數作為輸入,並從陣列中檢索相應元素。除了正整數外,也要能夠處理負整數,負整數會從陣列末尾計算。以下為使用範例
const arr = ["Explain", "This"];
arr.at(0); // Explain
arr.at(1); // This
arr.at(2); // undefined
arr.at(-1); // This
arr.at(-2); // Explain
arr.at(-3); // undefined
本題解答
以下是本題的解答,詳細解題思路可以在 E+ 會員方案 看到。如果想練習更多題目,推薦可以到 GreatFrontEnd 上練習。
解法
Array.prototype.at = function (index) {
const actualIndex = index >= 0 ? index : index + this.length;
return this[actualIndex];
};