1 背景:js中经常使用if(obj), 判断当前对象是否为空, 或者if(!obj)
if(obj){
}else{
}
if(!obj){
}else{
}
2 引发的问题,这里会包含多种情况
- 有五种情况,对象本身作为条件时,值为false:
- 未初始化,空串,null, false布尔值,数字0
3 使用的初衷:判断对象是否为空,经常(==null), 但又纠结是不是undefined
- 不知道怎么判断 undefined,索性来个if(obj)
- 但实际上 if(obj == null), 无论是null, undefined都为true
- 也补上undefined判断方法
if(typeof(obj) == 'undefined'){
console.log("is undefined")
}else{
console.log("is defined")
}