ECMAScript 新提案:.findLast()和.findLastIndex()從尾到頭搜尋陣列

前端小智發表於2022-04-20
作者:knaagar
譯者:前端小智
來源:dev

有夢想,有乾貨,微信搜尋 【大遷世界】 關注這個在凌晨還在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收錄,有一線大廠面試完整考點、資料以及我的系列文章。

查詢陣列元素

下面有三種方法從頭到尾查詢陣列元素。

方法一:

['a', 'b', 'a'].indexOf('a')  // 0
['a', 'b', 'a'].indexOf('c')  // -1

方法二:

['a1', 'b', 'a2'].find(x => x.startsWith('a')) // 'a1'
['a1', 'b', 'a2'].find(x => x.startsWith('c')) // undefined

方法三:

['a1', 'b', 'a2'].findIndex(x => x.startsWith('a')) // 0
['a1', 'b', 'a2'].findIndex(x => x.startsWith('c')) // -1

最新提案引入了 findLastfindIndex 方法,用法如下:

['a1', 'b', 'a2'].findLast(x => x.startsWith('a')) // 'a2'
['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a')) // 2

3.簡單的實現方式

下面,我們簡單來實現一下.findLast().findLastIndex():

.findLast()

function findLast(arr, callback, thisArg) {
  for (let index = arr.length-1; index >= 0; index--) {
    const value = arr[index];
    if (callback.call(thisArg, value, index, arr)) {
      return value;
    }
  }
  return undefined;
}

.findLastIndex()

function findLastIndex(arr, callback, thisArg) {
  for (let index = arr.length-1; index >= 0; index--) {
    const value = arr[index];
    if (callback.call(thisArg, value, index, arr)) {
      return index;
    }
  }
  return -1;
}

polyfill

如果你想先提前體驗,可以在 core-js 中引入。

地址:https://github.com/tc39/propo...


程式碼部署後可能存在的BUG沒法實時知道,事後為了解決這些BUG,花了大量的時間進行log 除錯,這邊順便給大家推薦一個好用的BUG監控工具 Fundebug

原文:https://2aliy.com/2022/03/arr...

交流

有夢想,有乾貨,微信搜尋 【大遷世界】 關注這個在凌晨還在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收錄,有一線大廠面試完整考點、資料以及我的系列文章。

相關文章