假设我有这样一个片段,
let arr = [{...},{...} ...]// huge array of objects;
arr.forEach(i => {
if(someOtherProperty == "one") {
...
} else if(someOtherProperty == "two") {
...
}...
})
基本上,我在循环中有一个 if-else-if 阶梯。
条件不依赖于数组项。
我想知道是否可以在执行循环之前评估 if 条件,因为在整个循环运行期间条件是静态/恒定的
我能想到的几种方法是
- 将循环保留在每个 if/else block 中。这样 if 条件将只执行一次,但我有更多代码。
使用像这样的对象
let condition = { one: someOtherProperty == "one", two: someOtherProperty == "two", ... }
并在if(condition.one)等条件下使用。
请提出更好的方法来处理这种情况,以提高效率。
最佳答案
我认为在这种情况下,条件语句中的代码存在巨大差异,您可以使用以下方法使您的代码看起来更好:
let arr = [1, 2, 3, 4, 5];
let str = "one";
const conditions = {
"one": function(item, index) {
console.log("one", item);
},
"two": function(item, index) {
console.log("two", item);
}
}
arr.forEach(conditions[str]);
或者,如果您想坚持基础知识,您也可以这样做:
let arr = [1, 2, 3, 4, 5];
let str = "one";
var one = function(item, index) {
console.log("one", item);
};
var two = function(item, index) {
console.log("two", item);
};
switch (str) {
case "one":
arr.forEach(one);
break;
case "two":
arr.forEach(two);
break;
}
关于javascript - 有没有办法确定 if static/constant 的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521159/