当你将其他类型的值转换为布尔类型时,JavaScript 将根据以下规则进行转换:
- false 类型的值转换为 false,例如:false、0、空字符串("")、null、undefined、NaN。
- true 类型的值转换为 true,例如:true、1、任何非空字符串、任何对象,甚至是字符串 "false" 和 "0"。
- 对象、函数和数组类型的值永远转换为 true。
下面是各类型值转化为Boolean的结果:
- Boolean 类型:在布尔上下文中,Boolean true 转换为 true,Boolean false 转换为 false。
- Number 类型:如果值是 +0、-0、NaN 或者 null,则转换为 false,其他情况转换为 true。
- BigInt 类型:如果值是 0n,则转换为 false,其他情况转换为 true。
- String 类型:如果值是空字符串,则转换为 false,其他情况转换为 true。
- Null 类型:转换为 false。
- Undefined 类型:转换为 false。
- Object 类型:转换为 true。
举个例子:
Boolean(0) // false Boolean("") // false Boolean(undefined) // false Boolean(null) // false Boolean(NaN) // false Boolean("0") // true Boolean("false") // true Boolean({}) // true Boolean([]) // true Boolean(function() { return true; }) // true