Lodash - findIndex 方法
语法
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
此方法与 _.find 类似,不同之处在于它返回谓词返回真值的第一个元素的索引,而不是元素本身。
参数
array (数组) − 要检查的数组。
[predicate=_.identity] (函数) − 每次迭代调用的函数。
[fromIndex=0] (数字) −要搜索的索引。
输出
(number) − 返回找到的元素的索引,否则返回 -1。
示例
var _ = require('lodash'); var users = [ { user: 'Sam', active: false }, { user: 'Ted', active: true }, { user: 'Julie', active: false } ]; var result = _.findIndex(users, function(user) { return !user.active; }); console.log(result); result = _.findIndex(users, ['active', false]); console.log(result);
将上述程序保存在tester.js中。运行以下命令执行该程序。
命令
\>node tester.js
输出
0 0