[Easy] 實作 Array.prototype.at

2024年3月8日

💎 加入 E+ 成長計畫 與超過 300+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

題目描述

請實作 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+ 成長計畫看到

解法

Array.prototype.at = function (index) {
  const actualIndex = index >= 0 ? index : index + this.length;
  return this[actualIndex];
};
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們