JavaScript 中逻辑表达式的短路计算

Short-Circuit Evaluation of Logical Expressions in JavaScript

本文关键字:短路 计算 表达式 JavaScript      更新时间:2023-09-26

我正在学习 JavaScript 并浏览 JavaScript: The Complete Reference, Third Edition 2012.考虑同一本书的摘要。

像许多语言一样,JavaScript 在解释器有足够的信息来推断结果后,就会缩短逻辑 AND (&&)逻辑 OR (||) 表达式的计算。例如,如果 || 运算的第一个表达式为 true,则计算表达式的其余部分实际上没有意义,因为无论其他值如何,整个表达式的计算结果都将为 true。类似地,如果 && 运算的第一个表达式的计算结果为 false,则无需继续计算右侧操作数,因为整个表达式将始终为 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.

这背后的原因是什么?

x 是 5,

即二进制 101,(x>>= 5) 因此为零,x 被赋值为零,并且不执行第一条语句中的 y++。

(x <<5) 同样为零,因为 x 现在为零,因此第二条语句中的 y++ 也不会执行。y 的值保持为 10,因为没有执行 y++。

我不知道你的作者从哪里得到 y == 11,这是错误的。

IDE错误是一个红鲱鱼 - 它不理解您的文件包含javascript(或者您错误地删除了javascript),并试图将其解析为XML/HTML。