JavaScript 中的雙感嘆號運算子示例

JavaScript 雙感嘆號 !!(not not)
提供與布林表示式相同的結果 (True, False)。JavaScript 中的雙感嘆號運算子是一元邏輯運算子 !(not)
的單次重複。
帶有 False
輸出的 JavaScript 雙感嘆號示例
下面是一個使用雙感嘆號運算子的簡短示例,以布林值表示輸出。條件是 true
不是 false
,這就是!true
導致 false
值的原因。
我們建立一個變數並分配一個帶有雙感嘆號 falseOrTrue = !!"";
的空字串。在最後一步,document.write(falseOrTrue);
,用於變數輸出。
<script>
//JavaScript code starts from here
var falseOrTrue;
//In this case the given falseOrTrue variable is initlizes to store the result
//Double Exclamation operator checks the string is true or false
falseOrTrue = !!"";
//Now string is empty the result will be false
document.write(falseOrTrue);
</script>
輸出:
false
你可以自己執行程式碼並檢查輸出。現在我們將執行另一個示例來獲得 true
輸出。
帶有 True
輸出的 JavaScript 雙感嘆號示例
以下示例包含變數 var falseOrTrue;
作為上面示例的變數。我們使用雙感嘆號運算子建立一個空物件名稱。
物件中儲存的值不為空。當我們呼叫變數時,它顯示值為 true
。
<script>
//JavaScript code starts from here
var falseOrTrue;
//In this case the given object is empty
//In this case the given falseOrTrue variable is initlizes to store the result
falseOrTrue = !!{
items: 1
};
//Now object is not empty the result will be true
document.write(falseOrTrue);
</script>
輸出:
true
JavaScript 中的雙感嘆運算子!!
中的 False
和 True
值
檢視錶格並檢視 !!value
結果。
value │ !!value
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
false │ false
true │ true
null │ false
undefined │ false
0 │ false
-0 │ false
1 │ true
-5 │ true
NaN │ false
'' │ false
'hello' │ true
所有的假值都是 false
,而真值在!!
運算子中是 true
。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe