_.lastIndexOf

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

_.lastIndexOf 方法用于查找给定元素在数组中的最后一次出现的索引位置。如果元素不存在于数组中,则返回 -1。这个方法与 JavaScript 原生的 Array.prototype.lastIndexOf 方法非常相似,但 Lodash 的版本可以支持更复杂的查找条件,比如使用迭代函数来确定元素是否匹配。

  1. _.lastIndexOf 的作用

    • _.lastIndexOf(array, value, [fromIndex=array.length-1]) 这个方法用于从右到左遍历数组,以查找给定值的最后一个索引。
  2. _.lastIndexOf 的参数

    • array:要搜索的数组。
    • value:要搜索的值。
    • **[fromIndex=array.length-1]**:开始搜索的索引值,默认为数组的最后一个索引。
  3. _.lastIndexOf 的返回值

    • 返回匹配值的索引值,如果未找到匹配项,则返回 -1。

使用示例

假设我们有一个数组,并且想要找到某个元素最后一次出现的索引位置:

// 使用原生 JavaScript
const array = [1, 2, 3, 1, 2, 3];
const lastIndex = array.lastIndexOf(2);
console.log(lastIndex); // 输出 4

// 使用 Lodash
const lastIndexLodash = _.lastIndexOf(array, 2);
console.log(lastIndexLodash); // 输出 4
_.lastIndexOf([1, 2, 1, 2], 2);
// => 3
 
// Search from the `fromIndex`.
_.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

在这个例子中,无论是使用原生 JavaScript 还是 Lodash,结果都是相同的,因为我们在查找数字 2 在数组中的最后一次出现位置。

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