JS-如果可以同时满足多个条件,则哪个条件可以运行? [英] JS - If multiple conditions can be true at the same time, which one runs?
问题描述
如果多个if语句可以同时为真,那么JS如何确定要运行哪个语句?在下面的示例中,我知道很酷,现在我对自己有很多墨西哥玉米片."将被退回,但我只是想知道如何确定?如果不是 friendsAtYourParty === 0
,而是 friendsAtYourParty<怎么办?3
(很酷,现在我对自己有很多墨西哥玉米片."会再次返回,但是为什么呢?).我在想,也许是更具体/更接近胜利"价值的那个?
If multiple if-statements can be true at the same time, how does JS determine which one to run? In the example below, I know "Cool, now I have a lot of nachos to myself." will get returned, but I just wonder how that is determined? What if instead of friendsAtYourParty === 0
it would be friendsAtYourParty < 3
("Cool, now I have a lot of nachos to myself." would get returned again, but why?). I was thinking maybe the one that is more specific/closer to the value "wins"?
if (friendsAtYourParty === 0) {
console.log("Cool, now I have a lot of nachos to myself.");
} else if (friendsAtYourParty < 4) {
console.log("Perfect amount to play some Mario Kart.");
} else {
console.log("Wooooo turn on the dance music!");
}
推荐答案
当您拥有 if/else
链 only 时,第一个 if
将执行匹配的条件.毕竟,这就是 if/else
的工作方式:
When you have an if/else
chain only the first if
condition that matches would be executed. After all, that's how if/else
works:
if (condition) {
//only executed when condition is true
} else {
//only executed when condition is false
}
当条件为 true
时, else
部分将不会执行.如果您有多个 if/else
The else
part will NOT execute when the condition is true
. Nothing changes when you have more than one if/else
:
if (condition1) {
//only executed when condition1 is true
} else if (condition2) {
//only executed when condition2 is true and condition1 is false
} else {
//only executed when both condition1 and condition2 are false
}
if/else
链描述了以下逻辑流程,因此为什么总是对其进行可预测的评估:
An if/else
chain describes the following logic flow, hence why it will always be evaluated predictably:
这篇关于JS-如果可以同时满足多个条件,则哪个条件可以运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!