聊一聊JS中布尔值为false哪点事儿

在JavaScript中布尔值为false总共有六种情况:NaN , 0 , false , “”(双引号)或 ‘’(单引号) ,null , undefined下面分别详细介绍:

  1. NaN (非数值,不能计算结果时)
//转化为布尔值
alert(Boolean(NaN)); //false

//对应的类型(typeof值)
alert(typeof(NaN)); //number
  1. 0 (数字0
    注意点:字符串 “0” 的布尔值为 true
//转换为布尔值
alert(Boolean(0)); //false

//对应的类型(typeof值)
alert(typeof(0)); //number
  1. false(布尔类型的false)
    注意点:字符串类型的 “false" 布尔值为 true
//转换为布尔值
alert(Boolean(false)); //false

//对应的类型(typeof值)
alert(typeof(false)); //boolean
  1. 引号 (“” (双引号) 或 ‘’(单引号))
    注意点:空字符串,引号中间有空格时布尔值为 ture
//转换为布尔值
alert(Boolean(""));//false
alert(Boolean(''));//false

//对应的类型(typeof值)
alert(typeof("")); //string
alert(typeof('')); //string
  1. null (空值)
//转换为布尔值
alert(Boolean(null)); //false

//对应的类型(typeof值)
alert(typeof(null)); //object

6 . undefined (没有定义)

//转换为布尔值
alert(Boolean(undefined)); //false

//对应的类型(typeof值)
alert(typeof(undefined); //undefined

注意点:处理上述概括的 6 种值转化为布尔值为 false 外,其他转化为布尔值的情况都为 ture ,空数组,空对象,负值转化为布尔值也为true

看完以上介绍,你是不是记住了什么情况布尔值为true,什么情况布尔值为false了。总之把布尔值为false那六种值,以及比较特殊的情况记下,就大功告成了。
如果想深入了解怎么用typeof运算符判断变量是什么类型的请点击我

发布了41 篇原创文章 · 获赞 49 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/wls666/article/details/89001267
今日推荐