当Boolean类型与字符串类型,整型做比较时Boolean会转成整型

136 阅读1分钟

当Boolean类型与字符串类型,整型做比较时Boolean会转成整型

今天写了一个关于取消全选的题目,当时还不知道<input type="checkbox" checked="checked">中获取它的checked属性值是boolean类型,将他当作了字符串"checked",于是拿来和字符串做了比较,发现始终程序都不对,查找资料得知,checked的属性值是boolean类型才将程序写对,但是转念一想,为什么一个boolean类型可以和字符串类型做比较呢?

于是开始实验

var a=true;
console.log(a,typeof(a));
if(a==1){
      console.log("a==1",typeof(a));
}else{
     console.log("a!=1",typeof(a));
	}

返回值是a==1

image.png

var a=true;
    console.log(a,typeof(a));
if(a==0){
    console.log("a==0",typeof(a));
}else{
    console.log("a!=0",typeof(a));
}

image.png

var a=false;
console.log(typeof(a));
if(a==0){
    console.log("a==0",typeof(a));
}else{
    console.log("a!=0",typeof(a));
}

image.png

由此可得,boolean类型和整型比较时会转换成整型,false为0,trun为整型1

根据ECMAScript规范,第11.9.3节"抽象平等比较算法":

The comparison x == y, where x and y are values, produces true or
false. Such a comparison is performed as follows:

  • If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

因此,在if (1 == true)中,true被强制为Number,即Number(true),其结果为1,从而产生最终的if (1 == 1),即true。

从Number(false) == 0开始,if (0 == false)是完全相同的逻辑。

当您使用严格等于运算符===时,不会发生这种情况:

11.9.6 The Strict Equality Comparison Algorithm

The comparison x === y, where x and y are values, produces true or
false. Such a comparison is performed as follows:

  • If Type(x) is different from Type(y), return false.
  • 这回答了我的问题-布尔值将转换为Number吗?答案是-布尔值转换为数字

详细信息请看 www.codenong.com/12236271/