声明定义
- 字面量定义布尔值
- 对象方式定义布尔值 ```javascript let foo = true; let bar = new Boolean(false);
console.log(foo,bar);
<a name="VJZzz"></a>### 隐式转换基本上所有类型都可以隐式转换为 Boolean类型。| 数据类型 | true | false || --- | --- | --- || String | 非空字符串 | 空字符串 || Number | 非0的数值 | 0 、NaN || Array | 数组不参与比较时 | 参与比较的空数组 || Object | 所有对象 | || undefined | 无 | undefined || null | 无 | null || NaN | 无 | NaN |注意:1. 当与boolean类型比较时,会将两边类型统一为数字1或0。1. 如果使用Boolean与数值比较时,会进行隐式类型转换 true转为1,false 转为0。1. 引用类型的Boolean值为真,如对象和数组。```javascriptconsole.log(3 == true); // falseconsole.log(0 == false); // trueif ([]) console.log('true'); // trueif ({}) console.log('true'); // true
显式转换
- 使用 !! 转换布尔类型。
- 使用 Boolean 函数可以显式转换为布尔类型。
console.log(!!3); // trueconsole.log(Boolean(0)); // false
