如何在JavaScript中将值转换为布尔值?

三种将值转换为boolean的方法。在这3种方法中,有2种方法在其中包含Boolean关键字,而另一种方法是其中包含符号!!的新方法用来。让我们详细讨论它们。

使用布尔键

示例

在以下示例中,实现了在其中使用Boolean 关键字的方法,并显示了结果,如输出所示。

<html>
<body>
<script>
   const isTrue = 'Golden State Warriors';
   document.write(new Boolean(isTrue));
   document.write("</br>");
   document.write(Boolean(isTrue));
</script>
</body>
</html>

输出结果

true
true


使用!!

示例

在下面的示例中,使用symbol(!!)代替Boolean关键字将值转换为Boolean。

<html>
<body>
<script>
   const isTrue = 'Golden State Warriors';
   document.write(!!isTrue);
</script>
</body>
</html>

输出结果

true