将 String 类型转换为布尔类型
只要字符串中有内容都会转换为 true, 只有字符串中没有内容才会转换为 false
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let strOne = "abc";
let strTwo = "";
console.log(Boolean(strOne));
console.log(Boolean(strTwo));
console.log(typeof Boolean(strTwo));
console.log(typeof Boolean(strTwo));
</script>
</head>
<body>
</body>
</html>
将 Number 类型转换为布尔类型
只有数值是 0 才会转换为 false, 其它的都会转换为 true,如果是 NaN 也会转换为 false
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let numOne = 999;
let numTwo = -123;
let numThree = -0;
let numFour = 0;
let flagOne = Boolean(numOne);
let flagTwo = Boolean(numTwo);
let flagThree = Boolean(numThree);
let flagFour = Boolean(numFour);
console.log(flagOne);
console.log(typeof flagOne);
console.log(flagTwo);
console.log(typeof flagTwo);
console.log(flagThree);
console.log(typeof flagThree);
console.log(flagFour);
console.log(typeof flagFour);
</script>
</head>
<body>
</body>
</html>
将 undefined 类型转换为布尔类型
undefined 会转换为 false
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let value = undefined;
let flag = Boolean(value);
console.log(flag);
console.log(typeof flag);
</script>
</head>
<body>
</body>
</html>
将 null 类型转换为布尔类型
null 会转换为 false,空字符串 / 0 / NaN / undefined / null 会转换成 false, 其它的都是 true
在 JavaScript 中如果想将基本数据类型转换为布尔类型, 那么只需要调用 Boolean(常量 or 变量) 即可转换
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let value = null;
let flag = Boolean(value);
console.log(flag);
console.log(typeof flag);
</script>
</head>
<body>
</body>
</html>
注意点:在 JavaScript 中 NaN
属于 Number 类型
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let num = NaN;
console.log(num);
console.log(typeof num);
let flag = Boolean(num);
console.log(flag);
console.log(typeof flag);
</script>
</head>
<body>
</body>
</html>