_.findLastIndex

栏目: Javascript 发布时间:2024-12-27

_.findLastIndex函数用于查找数组中最后一个满足提供的谓词(predicate)函数的元素的索引。与 _.findIndex 相反,_.findLastIndex 会从数组的末尾开始迭代,直到找到满足条件的元素或者迭代完整个数组。如果没有找到满足条件的元素,则返回 -1

语法

_.findLastIndex(array, [predicate=_.identity])
  • array (Array): 要搜索的数组。
  • [predicate=_.identity] (Function): 每次迭代调用的函数。

参数

  • array:要搜索的数组。
  • predicate(可选):一个函数,它接受数组中的元素作为参数,并返回一个布尔值。如果函数返回 true,则迭代将停止,并返回当前元素的索引(但因为是从后往前迭代,所以这是最后一个满足条件的元素的索引)。如果省略,默认使用 _.identity 函数,但通常在使用 _.findLastIndex 时,你会提供一个自定义的谓词函数来定义满足条件的元素。

返回值

(number): 返回最后一个满足谓词函数的元素的索引。如果没有找到,则返回 -1

示例

// 查找数组中最后一个大于 2 的元素的索引
const numbers = [1, 2, 3, 4, 3, 2, 1];
const lastIndex = _.findLastIndex(numbers, n => n > 2);
console.log(lastIndex);
// => 4(因为数组中最后一个大于2的元素是索引为4的3)

// 查找数组中最后一个值为 'b' 的字符串的索引
const strings = ['a', 'b', 'c', 'a', 'b'];
const lastStringIndex = _.findLastIndex(strings, str => str === 'b');
console.log(lastStringIndex);
// => 4(因为数组中最后一个值为'b'的元素是索引为4的'b')

// 如果没有元素满足条件,则返回 -1
const noMatchIndex = _.findLastIndex(numbers, n => n > 10);
console.log(noMatchIndex);
// => -1

在上面的示例中,_.findLastIndex 从数组的末尾开始迭代,并返回最后一个满足谓词函数的元素的索引。如果数组中没有元素满足条件,则返回 -1。这使得 _.findLastIndex 在处理需要查找最后一个符合条件元素的情况时非常有用。

本文地址:https://www.tides.cn/p_js-lodash-findLastIndex