javascript - Lodash,循环调用函数并返回第一个匹配结果

标签 javascript typescript lodash

我想迭代对象数组,调用它们的方法。如果该方法的结果满足某些条件。我想立即返回该结果。我写了这个:

public getFirstMatch(value: string, allValues: string[]): Result {
    let foundResult = undefined;
    _.find(this.myArrayofMatchers, matcher => {
        let result = matcher.isMatch(value, allValues);
        if(result.isMatch){
            foundResult = result;
            return true;
        }
    })

    return foundResult || new Result(false);
}

它有效,但看起来笨拙且不清楚。恕我直言,_.find 并不能清楚地表明我正在尝试做什么,因为我不关心实际的匹配器。事实上 foundResult 需要存在,但我觉得这很丑陋。而且它似乎需要更长的时间。 这里有什么我可以做得更好的吗?有更好的 lodash 函数吗?

顺便说一句,这就是我的想法,使用 for 循环

public isMatch(value: string, allValues: string[]): Result {
    for (let i = 0; i < this.myArrayofMatchers.length; i++){
        let result = this.myArrayofMatchers[i].isMatch(value, allValues);
        if (result.isMatch) {
            return result;
        }
    }
    return new Result(false);
}

最佳答案

您正在使用 _.find,就像 _.foreach 一样。这不好。 Lodash find 返回值,所以你应该利用它。

您的方法应如下所示:

public getFirstMatch(value: string, allValues: string[]): Result {
    const foundResult = _.find(
        this.myArrayofMatchers,
        matcher => matcher.isMatch(value, allValues).isMatch
    );

    return foundResult || new Result(false);
}

关于javascript - Lodash,循环调用函数并返回第一个匹配结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544719/

相关文章:

javascript - 过滤一个字段具有多个值的属性 - List.js 和 Filter.js

javascript - IE9 中的 D3 : "Invalid argument" error using d3. js

javascript - 如何为 RxJS Observable 的每次发射创建一个新对象?

javascript - 通过值为数组的键组合两个对象

javascript - Lodash - 搜索嵌套数组并返回对象

javascript - 使@media max-width 的行为与 $(window).width 相同

php - 包含的 PHP 页面中的 jQuery 代码

javascript - Angular 5 - 如何使用在组件上使用 InjectionToken 声明的提供者 key

angular - Ionic2 StorageModule/更新列表

javascript - Lodash - 使用具有多个属性的meanBy