定义

布尔类型表示逻辑实体,只有truefalse两个值,表示真假两个状态。

转为布尔

可以使用Boolean()转型函数将一个值转为布尔值。

undefined、null、+0、-0、NaN、false、""这七个转换成布尔值是假值,其他的都是真值。

console.log(Boolean(undefined));//false
console.log(Boolean(null));//false
console.log(Boolean(0));//false
console.log(Boolean(-0));//false
console.log(Boolean(NaN));//false
console.log(Boolean(''));//false
console.log(Boolean(false));//false
console.log(Boolean(' '));//true

注意: ''空字符的布尔值是false,' '空字符之间有空格结果就是true。

所有对象的转换结果都是true,

console.log(Boolean({}));//true
console.log(Boolean([]));//true
console.log(Boolean(new Boolean(false)));//true
console.log(Boolean(new Boolean(null)));//true
console.log(Boolean(new Boolean(undefined)));//true

实例方法

布尔对象有三个方法,均继承自Object对象,分别是toString() toLocaleString() valueOf()

toString()方法返回布尔值的字符串形式
toLocaleString()方法返回布尔值的字符串形式
valueOf()方法返回原始的布尔值

true.toString() // 'true'
true.toLocaleString() // 'true'
true.valueOf() // true

相关文章:

  • 2021-12-17
  • 2022-01-26
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
猜你喜欢
  • 2021-05-10
  • 2021-11-13
  • 2022-12-23
  • 2021-05-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案