gpt4 book ai didi

javascript - 有没有办法确定 if static/constant 的条件?

转载 作者:行者123 更新时间:2023-12-03 16:59:41 25 4
gpt4 key购买 nike

假设我有这样一个片段,

let arr = [{...},{...} ...]// huge array of objects;

arr.forEach(i => {
if(someOtherProperty == "one") {
...
} else if(someOtherProperty == "two") {
...
}...

})

基本上,我在循环中有一个 if-else-if 阶梯。

条件不依赖于数组项。

我想知道是否可以在执行循环之前评估 if 条件,因为在整个循环运行期间条件是静态/恒定的

我能想到的几种方法是

  1. 将循环保留在每个 if/else block 中。这样 if 条件将只执行一次,但我有更多代码。
  2. 使用像这样的对象

    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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com