美文网首页
js中布尔值为false的六种情况

js中布尔值为false的六种情况

作者: 而生lhw | 来源:发表于2022-03-02 11:18 被阅读0次

参考文献:https://www.cnblogs.com/zjx304/p/9782942.html

一、js中布尔值为false的六种情况,其他转化都为true

"!!" 将表达式进行强制转化为boolean值的运算,运算结果为true或者false。

  • 1、undefined (未定义,找不到值时出现)

  • 2、null (代表空值)

  • 3、false (布尔值的false,字符串“false”布尔值为true)

  • 4、0 -0 +0 (数字0,字符串“0”布尔值为true)

  • 5、NaN (无法计算结果时出现,表示“非数值” not a number)

  • 6、"" || '' (空字符串,中间有空格时也是true)

二、出现undefined的情况

1、未初始化的变量

  • 变量未定义 || 变量定义了没有赋值 || 函数形参未赋值

2、不返回任何结果的函数的调用结果

  • 函数return没有值
function show () {
  return
}
console.log(show())     // undefined
  • 函数没有return
function show() {
}
console.log(show())     // undefined

3、不存在的对象属性或方法

let obj = {
  name: '小名'
}
obj.age     // undefined

4、越界索引数组元素

const colors = ['blue', 'white', 'red']
colors[5]     // undefined
colors[-1]     // undefined

三、出现null的情况

1、在js的dom元素获取中,如果没有获取到指定的元素对象,结果一般是null。

2、Object.prototype.proto的值是null。

3、在正则捕获的时候,如果没有捕获到结果,默认也是null。

相关文章

网友评论

      本文标题:js中布尔值为false的六种情况

      本文链接:https://www.haomeiwen.com/subject/vdmsrrtx.html