[英]Short-Circuit Evaluation of Logical Expressions in JavaScript
我正在學習JavaScript,並通過JavaScript:完整參考,2012年第三版 。 考慮同一本書的摘要。
與許多語言一樣,一旦解釋器具有足夠的信息來推斷結果,JavaScript就會使邏輯AND(&&)或邏輯OR(||)表達式的求值短路 。 例如,如果||的第一個表達式 operation為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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.