在 JavaScript 中我们将 null 转成 布尔 类型可以使用 Boolean 方法。
Boolean(null)
Boolean 函数将 null 转换成布尔类型,如果返回 false。
返回 false。
使用 JavaScript 的 Boolean 方法将 null 转布尔
<!DOCTYPE html>
<html>
<head>
<title>使用 JavaScript 的 Boolean 方法将 null 转布尔</title>
<script type="text/javascript">
console.log("嗨客网(www.haicoder.net)");
var nul = null;
var bres = Boolean(nul);
console.log("null to bool =", bres, "type bres =", typeof bres);
var bres2 = Boolean(null);
console.log("null to bool =", bres2, "type bres2 =", typeof bres2);
</script>
</head>
</html>
程序运行后,控制台输出如下:
我们首先使用 var 关键字,声明了一个 变量 nul,赋值为 null,接着,我们使用 Boolean 函数将其转成 bool 类型,结果返回了 false。
最后,我们又直接使用了 Boolean 函数,将 null 转成了布尔类型,也返回了 false。
在 JavaScript 中我们将 null 转成布尔类型可以使用 Boolean 方法,Boolean 将 null 转成布尔永远返回 false。