假设我有以下代码片段:
let arr = [{...},{...} ...]// huge array of objects;
arr.forEach(i => {
if(someOtherProperty == "one") {
...
} else if(someOtherProperty == "two") {
...
}...
})
基本上,我在循环体内有一个if-else-if阶梯。
条件不依赖于数组项。
我想知道是否有可能在循环执行之前评估if条件,因为该条件在整个循环运行期间是静态/恒定的
我能想到的几种方法是:
- keep the loop inside each of the if/else blocks. This way the if condition will be executed only once but I have more codes.
Use an object like
let condition = { one: someOtherProperty == "one", two: someOtherProperty == "two", ... }
And use it in the condition like if(condition.one) and so on.
Please suggest a better way to deal with situations like this to improve the efficiency.
switch
语句吗?我不太确定我理解问题的意思。 - jhprattforEach()
而不是for
语句,因为存在上下文切换开销。 - Patrick Roberts