Boolean
对象是JS的三个包装对象之一。作为构造函数,他主要用于生成布尔值的包装对象实例。
let b = new Boolean(false)
typeof b; // 'object'
!!b; // true 所有对象对应的布尔值都是true
b.valueOf(); //false 返回实例对应的原始值
Boolean函数的类型转换作用
- Boolean对象除了可以作为构造函数,还可以单独使用,将任意值转为布尔值。这时Boolean就是一个单纯的工具方法。
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean('') // false
Boolean(NaN) // false
Boolean(1) // true
Boolean('false') // true
Boolean([]) // true
Boolean({}) // true
Boolean(function () {}) // true
Boolean(/foo/) // true
- 用双重的否运算符也可以讲任意值转换为对应的布尔值
!!undefined // false
!!null // false
!!0 // false
!!'' // false
!!NaN // false
!!1 // true
!!'false' // true
!![] // true
!!{} // true
!!function(){} // true
!!/foo/ // true
- 一些特殊值,用Boolean对象前加不加new,得于的结果完全相反
if (Boolean(false)) { // Boolean() 将任意类型的值转换为布尔值
console.log('true');
} // 无输出
if (new Boolean(false)) { // new Boolean()是把原始类型的值转换为对象,所有的对象的布尔都是true
console.log('true');
} // true
if (Boolean(null)) {
console.log('true');
} // 无输出
if (new Boolean(null)) {
console.log('true');
} // true