具有多个条件的javascript if语句是否测试了所有这些条件? [英] Does a javascript if statement with multiple conditions test all of them?
问题描述
在javascript中,当使用具有多个条件的if语句进行测试时,javascript是否会对它们进行全部测试,或者在测试它们之前是否会保释,如果它已经是假的?
In javascript, when using an if statement with multiple conditions to test for, does javascript test them all regardless, or will it bail before testing them all if it's already false?
例如:
a = 1
b = 2
c = 1
if (a==1 && b==1 && c==1)
javascript将测试所有这3个条件,或者在看到b不等于1之后,因此是假的,它会退出语句吗?
Will javascript test for all 3 of those conditions or, after seeing that b does not equal 1, and is therefore false, will it exit the statement?
从表演的角度来看,我问道。例如,如果我正在测试3个复杂的jQuery选择器,我宁愿不让jQuery遍历DOM 3次,如果它通过第一个显然会返回FALSE。 (在这种情况下,嵌套3 if语句更有意义)。
I ask from a performance standpoint. If, for instance, I'm testing 3 complex jQuery selectors I'd rather not have jQuery traverse the DOM 3 times if it's obvious via the first one that it's going to return FALSE. (In which case it'd make more sense to nest 3 if statements).
ADDENDUM:更多的好奇心,这个的正确用语是什么?我注意到你们很多人都使用短路一词。另外,有些语言会这样做而其他语言不这样做吗?
ADDENDUM: More of a curiosity, what is the proper term for this? I notice that many of you use the term 'short circuit'. Also, do some languages do this and others dont?
推荐答案
&&
运算符短路 - 也就是说,如果左边条件为假,则不会对正确的条件进行评估。
The &&
operator "short-circuits" - that is, if the left condition is false, it doesn't bother evaluating the right one.
同样, ||
如果左边条件为真,则运算符短路。
Similarly, the ||
operator short-circuits if the left condition is true.
编辑:虽然,你不应该担心性能,直到你进行基准测试并确定它是一个问题。过早的微观优化是可维护性的祸根。
Though, you shouldn't worry about performance until you've benchmarked and determined that it's a problem. Premature micro-optimization is the bane of maintainability.
这篇关于具有多个条件的javascript if语句是否测试了所有这些条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!