在 JavaScript 中實現 Array.prototype.lastIndexOf() 函式


JS 中的 lastIndexOf() 函式返回作為引數傳入陣列中的元素最後出現的位置,如果存在的話。如果不存在,則返回 -1。

例如 −

[3, 5, 3, 6, 6, 7, 4, 3, 2, 1].lastIndexOf(3) would return 7.

我們要求編寫一個 Javascript 函式,其與現有的 lastIndexOf() 函式具有相同的功能。

然後,我們必須使用剛建立的函式覆蓋預設的 lastIndexOf() 函式。我們將從後向前迭代,直到找到元素並返回其索引。

如果找不到元素,我們會返回 -1。

示例

以下是程式碼 −

const arr = [3, 5, 3, 6, 6, 7, 4, 3, 2, 1];
Array.prototype.lastIndexOf = function(el){
   for(let i = this.length - 1; i >= 0; i--){
      if(this[i] !== el){
         continue;
      };
      return i;
   };
   return -1;
};
console.log(arr.lastIndexOf(3));

輸出

這將在控制檯中產生以下輸出 −

7

更新於:2020-09-18

224 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.