JavaScript新功能介紹之findLast()和findLastIndex()
今天來看一個(gè) ECMAScript 提案:findLast() 和 findLastIndex()。
提案原因
在 JavaScript 中,可以通過 find() 和 findIndex() 查找數(shù)組中的值。不過,這些方法從數(shù)組的開始進(jìn)行遍歷:
const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; array.find(elem => elem.v > 3); // {v: 4} array.findIndex(elem => elem.v > 3); // 3
如果要從數(shù)組的末尾開始遍歷,就必須反轉(zhuǎn)數(shù)組并使用上述方法。這樣做就需要一個(gè)額外的數(shù)組操作。
基本使用
幸運(yùn)的是,Wenlu Wang 和 Daniel Rosenwasser 關(guān)于findLast() 和 findLastIndex() 的 ECMAScript 提案解決了這一問題。該提案的一個(gè)重要原因就是:語義。
它們的用法和find()、findIndex()類似,只不過是從后向前遍歷數(shù)組,這兩個(gè)方法適用于數(shù)組和類數(shù)組。
- findLast() 會(huì)返回第一個(gè)查找到的元素,如果沒有找到,就會(huì)返回 undefined;
- findLastIndex() 會(huì)返回第一個(gè)查找到的元素的索引。如果沒有找到,就會(huì)返回 -1;
const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; array.findLast(elem => elem.v > 3); // {v: 5} array.findLastIndex(elem => elem.v > 3); // 4 array.findLastIndex(elem => elem.v > 5); // -1
簡單實(shí)現(xiàn)
下面來簡單實(shí)現(xiàn)一下這兩個(gè)方法。
- 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; } const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; findLast(array, elem => elem.v > 3, array) // {v: 5} findLast(array, elem => elem.v > 5, array) // -1
- 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; } const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}]; findLastIndex(array, elem => elem.v > 3, array) // 4 findLastIndex(array, elem => elem.v > 5, array) // -1
lodash源碼
下面是 lodash 實(shí)現(xiàn)這兩個(gè)方法的源碼,供大家學(xué)習(xí)!
- findLast()
import findLastIndex from './findLastIndex.js' import isArrayLike from './isArrayLike.js' /** ?* This method is like `find` except that it iterates over elements of ?* `collection` from right to left. ?* ?* @since 2.0.0 ?* @category Collection ?* @param {Array|Object} collection The collection to inspect. ?* @param {Function} predicate The function invoked per iteration. ?* @param {number} [fromIndex=collection.length-1] The index to search from. ?* @returns {*} Returns the matched element, else `undefined`. ?* @see find, findIndex, findKey, findLastIndex, findLastKey ?* @example ?* ?* findLast([1, 2, 3, 4], n => n % 2 == 1) ?* // => 3 ?*/ function findLast(collection, predicate, fromIndex) { ? let iteratee ? const iterable = Object(collection) ? if (!isArrayLike(collection)) { ? ? collection = Object.keys(collection) ? ? iteratee = predicate ? ? predicate = (key) => iteratee(iterable[key], key, iterable) ? } ? const index = findLastIndex(collection, predicate, fromIndex) ? return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined } export default findLast
- findLastIndex()
import baseFindIndex from './.internal/baseFindIndex.js' import toInteger from './toInteger.js' /** ?* This method is like `findIndex` except that it iterates over elements ?* of `collection` from right to left. ?* ?* @since 2.0.0 ?* @category Array ?* @param {Array} array The array to inspect. ?* @param {Function} predicate The function invoked per iteration. ?* @param {number} [fromIndex=array.length-1] The index to search from. ?* @returns {number} Returns the index of the found element, else `-1`. ?* @see find, findIndex, findKey, findLast, findLastKey ?* @example ?* ?* const users = [ ?* ? { 'user': 'barney', ?'active': true }, ?* ? { 'user': 'fred', ? ?'active': false }, ?* ? { 'user': 'pebbles', 'active': false } ?* ] ?* ?* findLastIndex(users, ({ user }) => user == 'pebbles') ?* // => 2 ?*/ function findLastIndex(array, predicate, fromIndex) { ? const length = array == null ? 0 : array.length ? if (!length) { ? ? return -1 ? } ? let index = length - 1 ? if (fromIndex !== undefined) { ? ? index = toInteger(fromIndex) ? ? index = fromIndex < 0 ? ? ? ? Math.max(length + index, 0) ? ? ? : Math.min(index, length - 1) ? } ? return baseFindIndex(array, predicate, index, true) } export default findLastIndex
可用性
該提案目前處于第 3 階段,提案地址:https://github.com/tc39/proposal-array-find-from-last
此外,Lodash 和 Ramda 等庫為數(shù)組提供了findLast() 和 findLastIndex() 操作。
目前,在 Safari 15.4 中已經(jīng)支持了這兩個(gè)方法。期待更多瀏覽器支持這兩個(gè)方法!
總結(jié)
到此這篇關(guān)于JavaScript新功能介紹之findLast()和findLastIndex()的文章就介紹到這了,更多相關(guān)JS findLast() 和findLastIndex()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入淺析JavaScript的API設(shè)計(jì)原則
這篇文章主要介紹了JavaScript的API設(shè)計(jì)原則,包括接口的流暢性,一致性,參數(shù)的處理,可擴(kuò)展性,對(duì)錯(cuò)誤的處理,可預(yù)見性,注釋和文檔的可讀性,本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-06-06使用JS手寫一個(gè)類似?Laravel?驗(yàn)證器的表單驗(yàn)證器
這篇文章主要為大家介紹了使用JS手寫一個(gè)類似?Laravel?驗(yàn)證器的表單驗(yàn)證器實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06JavaScript讀取中文cookie時(shí)的亂碼問題的解決方法
讀取中文cookie時(shí)出現(xiàn)亂碼,下面是具體的解決方法,大家以后使用過程中,盡量不要用中文。2009-10-10TextArea設(shè)置MaxLength屬性最大輸入值的js代碼
TextArea中限制最大輸入長度,實(shí)現(xiàn)的方法種種,我們不在一一介紹,今天本文推薦一種簡單實(shí)用的方法,需要的朋友可以參考下2012-12-12EasyUI閃屏EasyUI頁面加載提示(原理+代碼+效果圖)
這篇文章主要介紹了EasyUI閃屏EasyUI頁面加載提示(原理+代碼+效果圖)的相關(guān)資料,需要的朋友可以參考下2016-02-02淺析JavaScript訪問對(duì)象屬性和方法及區(qū)別
這篇文章主要介紹了淺析JavaScript訪問對(duì)象屬性和方法及區(qū)別的相關(guān)資料,需要的朋友可以參考下2015-11-11Js和JQuery獲取鼠標(biāo)指針坐標(biāo)的實(shí)現(xiàn)代碼分享
這篇文章主要介紹了Js和JQuery獲取鼠標(biāo)指針坐標(biāo)的實(shí)現(xiàn)代碼分享,本文直接給出實(shí)現(xiàn)的代碼,需要的朋友可以參考下2015-05-05