【发布时间】:2015-03-04 23:09:35
【问题描述】:
我正在学习 JavaScript 并正在阅读 JavaScript:完整参考,2012 年第三版。考虑同一本书的摘要。
像许多语言一样,JavaScript 短路 逻辑与 (&&) 或 的求值>逻辑 OR (||) 表达式一旦解释器有足够的信息来推断结果。例如,如果 || 操作的第一个表达式是 true,那么评估真的没有意义表达式的其余部分,因为无论其他值如何,整个表达式的计算结果都会为真。同样,如果 && 操作的第一个表达式 的计算结果为 false,则无需继续计算右手操作数,因为整个表达式将始终为假。这里的脚本演示了短路评估的效果:
var x = 5, y = 10;
// The interpreter evaluates both expressions
if ( (x >>= 5) && (y++ == 10) )
document.write("The y++ subexpression evaluated so y is " + y);
// The first subexpression is false, so the y++ is never executed
if ( (x << 5) && (y++ == 11) )
alert("The if is false, so this isn't executed. ");
document.write("The value of y is still " + y);
我的 O/P 反映为:
The value of y is still 10
而作者为:
The y++ subexpression evaluated so y is 11
The value of y is still 11
我看到这个表达式没有被执行:
if ( (x >>= 5) && (y++ == 10) )
我在 Eclipse IDE 中看到上述表达式中第二个“&”下方的红线:
The entity name must immediately follow the '&' in the entity reference.
这背后的原因是什么?
【问题讨论】:
标签: javascript logical-operators short-circuiting