js数据类型强制转换--转换为Boolean

将其他的数据转换为Boolean

                -使用Boolean()函数
                         -数字-->布尔
                             除了0和NaN,其余的都是true
                         -字符串-->布尔
                             除了空串,其余都是true
                         -null和undefined都会转换为false
                         -对象也会转换为true

             -隐式类型转换
                      为任意的数据类型做两次非运算,即可将其转换为布尔值

                     例如:  
                     var a = "hello";
                     a = !!hello              //true

代码示例:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>强制类型转换--转换为Boolean</title>
<script type="text/javascript">
		
		var a=123;//true
		a=-123; //true
		a=0;//false;
		a=NaN;//false
		
		//调用Boolean()函数将a转换为布尔值
		a = Boolean(a);
		
		a = "hello";
		a = Boolean(a);
		
		a = "";
		a = Boolean(a);
		
		a = " ";
		a = Boolean(a);
		
		a = null;
		a = Boolean(a);
		
		a =undefined;
		a = Boolean(a);
		
		console.log(typeof a);
		console.log(a);
</script>
</head>
<body>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/dayun555/article/details/84063961