JS原始类型Boolean布尔类型

定义

布尔类型表示逻辑实体,只有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
优秀文章首发于聚享小站,欢迎关注!
原文地址:https://www.cnblogs.com/yesyes/p/15351841.html