【问题标题】:Lodash, call functions in a loop and return first matching resultLodash,循环调用函数并返回第一个匹配结果
【发布时间】:2016-09-17 08:40:36
【问题描述】:

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

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,恕我直言,并不能清楚地表明我正在尝试做什么,因为我不关心实际的 matcherfoundResult 需要存在的事实我觉得很丑陋。它似乎需要更长的时间。 这里有什么我可以做得更好的吗?有没有更好的 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);
}

【问题讨论】:

  • for (var matcher of _myArrray) 工作吗?
  • @georg 你是说foreach吗?我听说使用 lodash 是更好的做法,我担心效率(我知道,愚蠢的语言选择)。 for (let i = 0; i &lt; this.checkers.length; i++){ 工作,这是我现在正在使用的。
  • 不,我的意思是 for..of 循环,它的工作方式与您的第二个 sn-p 中的完全一样。如果普通语言结构有效,则无需使用库。
  • @georg Ahhhhh,我没听说过。干杯,我去看看。

标签: javascript typescript lodash


【解决方案1】:

您正在使用_.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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多