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