【发布时间】: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,恕我直言,并不能清楚地表明我正在尝试做什么,因为我不关心实际的 matcher。 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);
}
【问题讨论】:
-
for (var matcher of _myArrray)工作吗? -
@georg 你是说foreach吗?我听说使用 lodash 是更好的做法,我担心效率(我知道,愚蠢的语言选择)。
for (let i = 0; i < this.checkers.length; i++){工作,这是我现在正在使用的。 -
不,我的意思是
for..of循环,它的工作方式与您的第二个 sn-p 中的完全一样。如果普通语言结构有效,则无需使用库。 -
@georg Ahhhhh,我没听说过。干杯,我去看看。
标签: javascript typescript lodash