findLast()和findLastIndex()从尾到头搜索数组
目录
查找数组元素
下面有三种方法从头到尾查找数组元素。
方法一:
['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
最新提案引入了 findLast
和 findLastIndex
方法,用法如下:
['a1', 'b', 'a2'].findLast(x => x.startsWith('a')) // 'a2' ['a1', 'b', 'a2'].findLastIndex(x => x.startsWith('a')) // 2
简单的实现方式
下面,我们简单来实现一下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; }
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » findLast()和findLastIndex()从尾到头搜索数组
码云笔记 » findLast()和findLastIndex()从尾到头搜索数组