findIndex source npm

_.findIndex(array, [predicate=_.identity])

这个方法类似 _.find。除了它返回最先通过 predicate 判断为真值的元素的 index ,而不是元素本身。

参数

  1. array (Array)

    需要搜索的数组

  2. [predicate=_.identity] (Function|Object|string)

    这个函数会在每一次迭代调用

返回值 (number)

返回符合元素的 index,否则返回 -1

示例

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0

// 使用了 `_.matches` 的回调结果
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1

// 使用了 `_.matchesProperty` 的回调结果
_.findIndex(users, ['active', false]);
// => 0

// 使用了 `_.property` 的回调结果
_.findIndex(users, 'active');
// => 2