JavaScript boolean 类型
布尔类型
true
为真,flase
为假(false
是布尔值,而 Flase
只是标识符);
通常使用在 if/else
的判断语句中(如果需要的话,通常还会配合逻辑与 &&,逻辑或||来完成)
var a=52;
var b=30;
function demoBoolean(a, b) {
if (a>b){//2>30 -> false
console.log(a+" 大于 " +b)
}else if(a==b){//2==30 -> false
console.log(a+" 等于 " +b)
}else{
console.log(a+" 小于 " +b)
}
console.log(a>b);
console.log(a==b);
if(null){
console.warn("条件为真的时候才输出")
}else{
console.warn("if条件为假的时候才输出")
}
}
demoBoolean(a,b);
特性
- true 不一定 =1;flase 不一定 =0;
- 使用 boolean() 进行转换;任何数据类型的值调用 Boolean() 函数,都会返回一个 Boolean 值;也可以用 (!/!! 来转换)
- 转为 true 的
- Boolean 的 true 本身
- 任何非空字符串
- 任何非零数值
- 对象
- 转换为 flase
-
false 本身
-
空字符串
-
null 和 undefined;
-
0 和 NaN(
0 ==== -0
吗?可以输出看一下,是等于的)console.log(0===(-0));//true
-
- 转为 true 的
**为 false 值的是:**false 本身、空字符串、0、NaN、null、undefined;这些值要记住,很重要;
/* ................................非常重要。。。。。。。。。。
* 哪些值是false(false本身)
* 数字:0、-0 、NaN、
* 字符串:''(空字符串)
* null 、
* undefined、
* */
console.log("---------------------------------");
console.log(Boolean(0)); //false
console.log(Boolean(-0)); //false
console.log(Boolean(1)); //true
console.log(Boolean(-5)); //true
console.log(Boolean("222"));//true
console.log(Boolean('')); //false 空的字符串
console.log(Boolean(" ")); //true 包含空格的字符串
console.log("---------------------------------");
console.log(Boolean("0"));//true
console.log(Boolean(null));//false
console.log(Boolean(undefined));//false
console.log(Boolean({}));//true
console.log(Boolean(function () {}));//true
console.log(Boolean(false));//false
console.log("---------------------------------");
console.log(Boolean(55*"asd"));// NaN false
!
和 !!
! 是取反的意思;先将其它的数据类型转换为布尔类型;然后在取反;
!! 是将其他的数据类型取反再取反,结果是将数据转换为布尔类型,相当于 Boolean()
;
// ! !!
console.log("************************");
console.log(Boolean(0));//false
console.log(Boolean(!0));//true
console.log(!0);//true 原理: 0 隐式的调用Boolean方法Boolean(0) -> false -> !false ->true
console.log(!!0);// !(!false)->!true ->false
自身做布尔运算时候的转换
类型 | 规律 | 示例 |
---|---|---|
Object | 都是 true | alert(!![]) |
Number | 只是 0 和 NaN 是 false | alert(!!0) |
String | 只有空字符串是 false(不是空格字符串) | alert(!!”) |
Function | 都是 true | |
null,undefined | 都是 false |
总结:0、NaN、”、null、undefined、false 本身;只有这六个是 false 类型的;其它都是 true;
数据类型和逻辑运算规律表
【我手动画的转换图】
详细解说
类型 A | 类型 B | 比较时候的运算原理 | 说明 |
---|---|---|---|
对象 | 对象 | 比较是不是同一个内存地址,肯定不相等 | []==[] false |
对象 | 字符串 | 对象先转化为字符串,然后做比较 | - |
对象 | 布尔类型 | 两边都要先转为数字 (false 是 0,true 是 1);对象类型先转隐式调用 toString 方法,然后再 Number() | []==false,[]==0,[1]==1,[1]==true,[2]==true |
对象 | 数字 | 对象要转为数字,再进行比较(对象先隐式调用 toString 方法转换为字符串,然后再把这个字符串转化为数字,相当于字符串放到 number 这个方法中) | - |
数字 | 布尔 | 是进行数字的比较,布尔转为数字 | - |
数字 | 字符串 | 两边都要转换为数字再进行比较 | - |
布尔 | 字符串 | 两边都要转为数字再进行比较 | - |
null | undefined | True; 因为 undefined 派生自 null | - |
null/undefined | 其它所有类型 | Null 和 undefined 和其他类型比较都是 false;(这两个方法没有 toString 方法) | null==false,null==0,null==” |