如何优化嵌套if
How to optimize nested if?
嗨,我想知道有更好的方法吗?条件a比b更重要,b比c更重要,等等。
var slot = condition_a
if (!slot) {
slot = condition_b
if (!slot) {
slot = condition_c
if (!slot) {
slot = condition_d
if (!slot) {
slot = condition_e
}
}
}
}
if (slot) {
//do something
}
您执行OR:
if (condition_a || condition_b || condition_c || condition_d || condition_e) {
// do something
}
这相当于您的代码。如果条件评估为true
,则不检查以下条件(称为短路评估)。它可以进行这样的检查:
if (a===null || a.b===0) {
请注意,在同一个地方有这么多条件看起来像一种代码气味:可能有一些东西在语义上设计得不够。
您也可以像这样使用||
条件,
slot = condition_a||condition_b||condition_c||condition_d;
Fiddle 示例
如果您需要slot
有一个值(而不仅仅是在最后使用它来测试条件)
var slot = condition_a || condition_b || condition_c || condition_d || condition_e;
if (slot) {
// do soemthing
}
相关文章:
- 嵌套if语句中的else语句.这段代码如何知道要执行哪个else语句
- 嵌套if的javascript问题
- Javascript/JQuery嵌套if语句工作不正常
- for循环中嵌套if条件的setTimeout
- 嵌套if语句vs&&操作员javascript jquery
- Javascript 多个嵌套 if 语句不适用于 Rails 代码
- 如何避免这样的嵌套if语句
- 多个嵌套if语句未进行计算
- 如何优化嵌套if
- Javascript嵌套If语句
- 如何避免混乱的嵌套if-else或开关
- 是否可以在手把模板中嵌套if/else语句
- 如何将带有嵌套if语句的if-else语句转换为一个三元语句
- Noobish JavaScript嵌套If Else语句帮助/建议/指针/YouNameIt
- 如何在Jquery Javascript中使用嵌套if else
- 我有一个嵌套if的函数.我怎样才能做出'这个'指向构造函数.父
- 较短的嵌套if语句
- 如何缩短我的嵌套if/else语句
- 在JavaScript中重构嵌套if语句
- 在javascript中嵌套if else