JavaScript 如何将数字转换为布尔值
我们可以通过使用JavaScript中的 Boolean() 方法和 双重非运算符(!!) 将数字转换为布尔值。JavaScript的布尔值结果为true或false。然而,如果要将存储整数“0”或“1”的变量转换为布尔值“false”或“true”。
方法1:Boolean()方法
Boolean函数返回变量的布尔值。它还可以用于找到条件、表达式等的布尔结果。
语法:
Boolean(variable/expression)
示例 : 这个示例将一个数字转换为布尔值。
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h4>
Click the button to change the
number value into boolean.
</h4>
<button onclick="myFunction()">Change</button>
<p>The number value of the variable is :</p>
<p id="result"></p>
<script>
// Initializing boolvalue as true
var numvalue = 1;
// JavaScript program to illustrate boolean
// conversion using ternary operator
function myFunction() {
document.getElementById("result")
.innerHTML = Boolean(numvalue);
}
</script>
</center>
</body>
</html>
注意: 如果上述的 Boolean() 方法被调用为 Boolean(!numvalue) ,它会显示结果为“false”。同样地,如果调用为 Boolean(!!numvalue) ,结果会是“true”。
输出:
方法2:使用双重逻辑非(!!)运算符
该运算符将数值为零的数字转换为 false(假) ,并将其他所有数字转换为 true(真)。
示例: 在此示例中,我们将使用双重逻辑非运算符将数字转换为布尔值。
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h4>
Click the button to change the
number value into boolean.
</h4>
<button onclick="myFunction()">Change</button>
<p>The number value of the variable is :</p>
<p id="result"></p>
<script>
// Initializing boolvalue as true
var numvalue = (!!1)
// JavaScript program to illustrate boolean
// conversion using ternary operator
function myFunction() {
document.getElementById("result")
.innerHTML = (numvalue);
}
</script>
</center>
</body>
</html>
输出: