JS - 判断空值的方法(undefined、null)
在开发中我们常常要进行非空判断,而 JavaScript 中有两种特殊数据类型:undefined 和 null:
(2)如果变量有可能是数字 0 的话,使用上面的判断还不够严谨,可以使用下面方法:
- null: Null 类型,表示“空值”,代表一个空对象指针,使用 typeof 运算得到 “object”,所以我们可以认为它是一个特殊的对象值。
- undefined: Undefined 类型,当声明了一个变量未初始化时,得到的就是 undefined。
目前,null 和 undefined 基本是同义的,只有实际用法上有一些细微的差别:
下面通过样例演示如何判断一个变量是否为 null,或者 undefined。
- null 表示"没有对象",即该处不应该有值。
- undefined 表示"缺少值",就是此处应该有一个值,但是还没有定义。
1,仅判断是否为 undefined
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var a; var b = null ; if ( typeof (a) == 'undefined' ) { console.log( 'a 是 undefined' ); } else { console.log( 'a 不是 undefined' ); } if ( typeof (b) == 'undefined' ) { console.log( 'b 是 undefined' ); } else { console.log( 'b 不是 undefined' ); } |

2,仅判断是否为 null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var a; var b = null ; if (!a && typeof (a) !== 'undefined' && a != 0) { console.log( 'a 是 null' ); } else { console.log( 'a 不是 null' ); } if (!b && typeof (b) !== 'undefined' && b != 0) { console.log( 'b 是 null' ); } else { console.log( 'b 不是 null' ); } |

3,非空判断
(1)实际开发中我们可能不需要区分地这么细,而是只要简单地进行非空判断(如果变量为 undefined 或者为 null 都表示空),那么可以使用下面方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var a; var b = null ; if (!a) { console.log( 'a 为空' ); } else { console.log( 'a 不为空' ); } if (!b) { console.log( 'b 为空' ); } else { console.log( 'b 不为空' ); } |

(2)如果变量有可能是数字 0 的话,使用上面的判断还不够严谨,可以使用下面方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var a; var b = null ; var c = 0; if (!a && a != 0) { console.log( 'a 为空' ); } else { console.log( 'a 不为空' ); } if (!b && b != 0) { console.log( 'b 为空' ); } else { console.log( 'b 不为空' ); } if (!c && c != 0) { console.log( 'c 为空' ); } else { console.log( 'c 不为空' ); } |
