一、前言
最近在编写项目过程中,发现自己对if语句判断的时候,在面对一些0、字符串为空的情况下,自己犹豫了那么几秒
甚至有时候还可怕的写下了丑陋的代码
if(str !== ''){
// do some things
}
今天,特意写了这篇文章记录下,让自己长长记性,同时后面有空去翻翻红宝书
二、测试
考虑的情况有以下:
- 字符串为空
- 数值为零
- undefined
- null
- 对象不存在的属性
- NaN
字符串为空
if ('') {
console.log('访问空字符串,能通过')
}
// 没输出
数值为零
if (0) {
console.log('访问0,能通过')
}
// 没输出
undefined
if (undefined) {
console.log('访问undefined,能通过')
}
// 没输出
if(!undefined){
console.log('非undefined,能通过')
}
// 非undefined,能通过
null
if (null) {
console.log('null,能通过')
}
// 没输出
if(!null){
console.log('非null,能通过')
}
// 非null,能通过
对象不存在的属性
let obj = {
foo: "foo",
num: 0
}
if (obj.bar) {
console.log('访问对象不存在属性时候,能通过')
}
// 没输出
if (obj.foo) {
console.log('访问对象已存在属性时候,能通过')
}
// 访问对象已存在属性时候,能通过
NaN
if(NaN){
console.log('访问NaN,能通过')
}
// 没输出
if(!NaN){
console.log('不为NaN,能通过')
}
// 不为NaN,能通过