lodash里的_findtIndex()和_findLastIndex
1._.findIndex()
- 语法:
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
第一个值是要查找的数组
第二个值是查找的条件
第三个值是开始的索引值
返回找到元素的 索引值(index),否则返回 -1。
-
理解:
官方文档: lodash._findIndex
简单来说就是: 自左向右查找出满足条件的第一个数组元素的索引。 -
示例:
const myArr = [3, 3, 5, 2, 0, 1, 3, 1, 4, 5]
const result = _.findIndex(myArr, function (i) {
return i > 3
})
console.log(result)
// 结果为2
以上代码是自左向右查找数组myArr中元素>3的第一个元素的索引,很显然,索引为2的5明显>3,找到了5便不会往后面找了,最后输出结果是索引2.
const myArr = [3, 3, 5, 2, 0, 1, 3, 1, 4, 5]
const result = _.findIndex(
myArr,
function (i) {
return i > 3
},
3
)
console.log(result)
// 结果为8
以上代码是查找数组 myArr 中从索引3 ( 包括索引3 ) 开始自左向右满足元素 > 3 的元素的索引 . 从2开始找很显然遇到的第一个4是>3的 , 4对应的索引是8 , 所以最后的结果是8.
2._.findLastIndex()
- 语法
_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])
第一个值是要查找的数组
第二个值是查找的条件
第三个值是开始的索引值
返回找到元素的 索引值(index),否则返回 -1。
-
理解
官方文档: lodash._findLastIndex
简单来说就是: 自右向左查找出满足条件的第一个数组元素的索引。
3.示例
const myArr = [3, 3, 5, 2, 0, 1, 3, 1, 4, 5]
const result = _.findLastIndex(myArr, function (i) {
return i > 3
})
console.log(result)
// 结果为9
显而易见 从右往左来看大于3的就是索引为9的最后一项5 故结果为9
const myArr = [3, 3, 5, 2, 0, 1, 3, 1, 4, 5]
const result = _.findLastIndex(
myArr,
function (i) {
return i > 3
},
3
)
console.log(result)
// 结果为2
显而易见 从索引为3的2开始从右往左来看大于3的就是索引为2的5了 故结果为2