ES6 - 邏輯運算子



假設變數 A 的值為 10,B 的值為 20。

示例

var avg = 20;
var percentage = 90;
console.log("Value of avg: " + avg + " ,value of percentage: " + percentage);
var res = ((avg > 50) && (percentage > 80));
console.log("(avg>50)&&(percentage>80): ", res);
var res = ((avg > 50) || (percentage > 80));
console.log("(avg>50)||(percentage>80): ", res);
var res = !((avg > 50) && (percentage > 80));
console.log("!((avg > 50)&&(percentage>80)): ", res);

以上程式碼成功執行後,將顯示以下輸出。

Value of avg: 20 ,value of percentage: 90
(avg > 50)&&(percentage > 80): false
(avg > 50)||(percentage > 80): true
!((avg > 50)&&(percentage > 80)): true

短路運算子

&&|| 運算子用於組合表示式。

只有當兩個條件都返回 true 時,&& 運算子才會返回 true。讓我們考慮一個表示式 -

var a = 10
var result = ( a<10 && a>5)

在上面的示例中,a<10 和 a>5 是由 && 運算子組合的兩個表示式。這裡,第一個表示式返回 false。但是,&& 運算子要求兩個表示式都返回 true。因此,運算子跳過第二個表示式。

如果其中一個表示式返回 true,則 || 運算子返回 true。例如 -

var a = 10
var result = ( a>5 || a<10)

在上面的程式碼片段中,兩個表示式 a>5 和 a<10 由 || 運算子組合。這裡,第一個表示式返回 true。由於第一個表示式返回 true,因此 || 運算子跳過後續表示式並返回 true。

由於 && 和 || 運算子的這種行為,它們被稱為短路運算子。

廣告

© . All rights reserved.