当作为一个构造函数(带有运算符 new)调用时,Boolean() 将把它的参数转换成一个布尔值,并且返回一个包含该值的 Boolean 对象。

发布时间 2023-11-15 22:43:08作者: 龙陌

使用Boolean(value)方法可以强制转换任意值为boolean类型,除了以下六个值,其他都是自动转为true:

undefined
null
-0
+0
NaN
‘’(空字符串)
Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean(NaN) // false
Boolean('') // false

使用场景 const array = [3, 0, 6, 7, '', false]; array.filter(Boolean); // 输出 (3) [3, 6, 7]

console.log(new Boolean());//PrimitiveValue原始值为false
console.log(new Number());//PrimitiveValue原始值为0
console.log(new String());//PrimitiveValue原始值为""空字符串
console.log(new function(){});//PrimitiveValue原始值为{}

1)
当作为一个构造函数(带有运算符 new)调用时,Boolean() 将把它的参数转换成一个布尔值,并且返回一个包含该值的 Boolean 对象。
如果作为一个函数(不带有运算符 new)调用时,Boolean() 只将把它的参数转换成一个原始的布尔值,并且返回这个值。
2)
注释:如果省略 value 参数,或者设置为 0、-0、null、""、false、undefined 或 NaN,则该对象设置为 false。
否则设置为 true(即使 value 参数是字符串 "false")。