Nodejs lodash.findIndex第三个参数作用?

Nodejs lodash.findIndex第三个参数作用?

lodash.findIndex(array, callback, thisArg); findIndex 没有弄清楚thisArg这个参数是做什么的,还望解答~非常感谢啦!

3 回复

当然可以。lodash.findIndex 是一个非常有用的函数,用于在一个数组中查找满足条件的第一个元素的索引。该函数接受三个参数:arraycallbackthisArg。其中,thisArg 参数的作用是在执行 callback 函数时为其提供上下文(即 this 的值)。下面我们详细解释一下这个参数,并通过示例代码来说明其用法。

示例代码

假设我们有一个用户列表,每个用户对象包含 nameage 属性。我们想要找到年龄大于 30 的第一个用户的索引。为了实现这一点,我们可以使用 lodash.findIndex 函数。同时,我们将展示如何使用 thisArg 参数来改变 callback 函数内部的 this 值。

const _ = require('lodash');

// 用户列表
const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 },
  { name: 'Charlie', age: 40 }
];

// 定义一个回调函数
function checkAge(user) {
  return user.age > 30;
}

// 使用 lodash.findIndex 查找第一个符合条件的用户
const index = _.findIndex(users, checkAge);

console.log(index); // 输出: 1

// 现在让我们使用 thisArg 参数来改变 this 的值
const context = { threshold: 30 };

// 重新定义回调函数,使用箭头函数以保留外部的 this
const checkAgeWithContext = (user) => {
  return user.age > this.threshold;
};

// 使用 lodash.findIndex 并传入 thisArg 参数
const indexWithContext = _.findIndex(users, checkAgeWithContext, context);

console.log(indexWithContext); // 输出: 1

解释

  • thisArg 参数:在上述示例中,当我们调用 _.findIndex(users, checkAgeWithContext, context) 时,checkAgeWithContext 函数中的 this 将指向 context 对象。这意味着我们可以访问 context 对象中的属性(如 threshold),从而使得我们的回调函数更加灵活。

  • 回调函数:在第一个示例中,我们直接传递了一个普通函数 checkAge。而在第二个示例中,我们传递了一个使用箭头函数定义的 checkAgeWithContext,这样可以在 callback 中正确地引用外部的 this

通过这种方式,thisArg 参数允许你在调用 callback 函数时自定义 this 的值,从而增强了函数的灵活性和可重用性。


直观感觉是 callback 在调用的时候函数体用到 this 那么, this 就指向 thisArg.

lodash.findIndex 是一个非常有用的函数,用于在数组中查找满足条件的第一个元素的索引。它的完整签名是 lodash.findIndex(array, [predicate=_.identity], [fromIndex=0])。其中,第三个参数 thisArg 是用来指定在执行回调函数时使用的上下文(即 this 的值)。

示例代码

假设我们有一个对象数组,并且我们想要根据某个属性来查找第一个匹配的元素。我们可以使用 lodash.findIndex 来实现这一点,并通过 thisArg 参数来设置回调函数中的 this 上下文。

const _ = require('lodash');

// 示例数据
const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
];

// 定义一个类,该类将作为回调函数的上下文
class UserSearcher {
    constructor(targetId) {
        this.targetId = targetId;
    }

    // 回调函数
    isMatch(user) {
        return user.id === this.targetId;
    }
}

// 创建一个 UserSearcher 实例
const searcher = new UserSearcher(2);

// 使用 findIndex 查找第一个匹配的用户
const index = _.findIndex(users, searcher.isMatch.bind(searcher));

console.log(index); // 输出 1,因为 Bob 的 id 是 2

在这个例子中,searcher.isMatch.bind(searcher)isMatch 方法绑定到 searcher 对象上,这样在 isMatch 方法内部的 this 就会指向 searcher 对象。这使得我们可以方便地访问 targetId 属性。

解释

  • array: 要搜索的数组。
  • callback: 用于测试数组中的每个元素的函数。如果省略,则默认为 _.identity,即返回当前元素本身。
  • thisArg: 执行回调函数时用作 this 的值。

通过 thisArg 参数,你可以确保回调函数中的 this 始终指向你期望的对象,从而使得你的代码更加清晰和易于维护。

回到顶部