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