_.findIndex
栏目:
Javascript
发布时间:2024-12-27
_.findIndex
函数用于查找数组中第一个满足提供的谓词(predicate)函数的元素的索引。一旦找到满足条件的元素,迭代就会停止。如果没有找到满足条件的元素,则返回 -1
。
语法
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
array
(Array): 要搜索的数组。[predicate=_.identity]
(Function): 每次迭代调用的函数。[fromIndex=0]
(number): 开始搜索的索引位置。
参数
array
:要搜索的数组。predicate
(可选):一个函数,它接受数组中的元素作为参数,并返回一个布尔值。如果函数返回true
,则迭代将停止,并返回当前元素的索引。如果省略,默认使用_.identity
函数,它会返回参数本身(即会检查元素是否为假值,如false
、null
、0
、""
、undefined
和NaN
,但在_.findIndex
的上下文中,这通常不是预期的行为,因为_.identity
不会检查元素是否“满足条件”,而是直接返回元素值,这通常不是谓词函数的预期用途)。fromIndex
(可选):开始搜索的索引位置。如果为负值,则从数组末尾开始计算索引。默认为0
。
返回值
(number): 返回第一个满足谓词函数的元素的索引。如果没有找到,则返回 -1
。
示例
// 查找数组中第一个大于 2 的元素的索引
const numbers = [1, 2, 3, 4];
const index = _.findIndex(numbers, n => n > 2);
console.log(index);
// => 2
// 查找数组中第一个值为 'b' 的字符串的索引
const strings = ['a', 'b', 'c', 'b'];
const stringIndex = _.findIndex(strings, 'b');
// 注意:这里的用法是错误的,因为 'b' 不是一个函数。正确的做法是使用一个函数作为谓词:
const correctStringIndex = _.findIndex(strings, str => str === 'b');
console.log(correctStringIndex);
// => 1
// 从索引 2 开始查找数组中第一个大于 4 的元素的索引(不存在)
const nonExistentIndex = _.findIndex(numbers, n => n > 4, 2);
console.log(nonExistentIndex);
// => -1
注意:在上面的字符串示例中,我首先展示了一个错误的用法,即直接传递了一个字符串 'b'
作为谓词函数。这是不正确的,因为 _.findIndex
期望一个函数作为谓词。我随后展示了正确的用法,即传递了一个函数 str => str === 'b'
作为谓词。
本文地址:https://www.tides.cn/p_js-lodash-findIndex