gpt4 book ai didi

javascript - 将多个 if-else 语句转换为对象的 switch-case

转载 作者:行者123 更新时间:2023-11-30 08:23:43 25 4
gpt4 key购买 nike

我有一个对象,我必须在其中使用多个 if-else 语句来验证不同的值,如下所示是示例 javascript 代码段:

if(properties.values.a > 0 ){

}else if(properties.values.b > 0){

}else if(properties.values.c > 0){

}else if(properties.values.d > 0){

}else if(properties.values.e > 0){

}else{

}

我愿意将这个多重 if-else 语句替换为 switch-case。现在我想知道这对物体是否可行?如果可能的话,应该怎么走?

最佳答案

Switch 不应该这样工作。所以,不,这不受支持。作为解决方法,您可以这样做

switch (true) {
case (properties.values.a > 0):
...
case (properties.values.b > 0):
...
case (properties.values.c > 0):
...
case (properties.values.d > 0):
...
case (properties.values.e > 0):
...
}

不过,还是很丑,所以我建议你坚持使用 if/else。

关于javascript - 将多个 if-else 语句转换为对象的 switch-case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49276956/

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