学习资料笔记

小木的学习笔记

JS 中判断空值 undefined 和 null

2020-4-8 小木 前端

1.JS 中如何判断 undefined
var exp = undefined;
if (typeof(exp) == "undefined"){
    alert("undefined");
}

2.JS 中如何判断 null
var exp = null; 
if (!exp && typeof(exp) != "undefined" && exp != 0) { 
    alert("is null"); 
}

不正确的判断情况注意⚠️:
// exp 为 undefined 时,也会得到与 null 相同的结果,虽然 null 和 undefined 不一样。注意:要同时判断 null 和 undefined 时可使用本法。
var exp = null; 
if (exp == null) { // true
	alert("is null"); 
}

// 如果 exp 为 undefined 或者数字零,也会得到与 null 相同的结果,虽然 null 和二者不一样。注意:要同时判断 null、undefined 和数字零时可使用本法。
var exp = null; 
if (!exp) { // true
	alert("is null"); 
}

// exp 为 null 时,typeof 返回 object。
var exp = null; 
if (typeof(exp) == "null") { // false
	
}

标签: undefined null 判断空值