掌握JS的几种空判断(undefined、null、NaN)

判断是否为undefined

// 方法一
var a=undefined; 
if (typeof(a) == "undefined"){ 
	console.log("undefined"); 
}

// 方法二
var a=undefined;
if(a === undefined){
	console.log("undefined")
}

判断是否为null

var b= null; 
if (!b && typeof(b)!="undefined" && b!=0){ 
   console.log("null"); 
}

需要注意以下写法

var a=undefined;
var b=null;

if(a==null){ // 成立
    console.log("成功输出")
}
if(a===null){// 不成立,无输出
    console.log("成功输出")
}
if(b===null){// 成立
    console.log("成功输出")
}

简单说明下"“和”=":==是用来检测两个操作数是否相等的,是“值比较”,===是严格校验两个操作数是否严格相等,包括“值比较”和“类型比较”。

判断是否为NaN

var c= 0/0; 
if (isNaN(c) ){ 
   console.log("NaN"); 
}

NaN 表示非法,如果把 NaN 与任何值(包括其自身)作比较结果均是 false,所以不能使用 == 或 === 运算符判断某个值是否是 NaN。

判断是否为undefined、null或NaN(粗判断)

var d= null; 
if (!d) { 
   console.log("null or undefined or NaN"); 
}

判断输入框的值是否为空

var str = ' ' 
if (str.replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
	console.log("输入值为空"); 
}

一般输入框的判断会去除空格,如果是number类型,要先转换成string,即

var num= 0 
if (num.toString().replace(/(^\s*)|(\s*$)/g, '').length <= 0) {
	console.log("输入值为空"); 
}

判断对象是否为空

// 方法一
var e={}
if(Object.keys(e).length === 0){
	console.log("{}")
}

// 方法二
var e={};
if(JSON.stringify(e) == "{}"){
	console.log("{}")
}

判断数组是否为空

var f=[];
if (f.length == 0){
    console.log("[]")
}

转载:https://blog.csdn.net/worshipme/article/details/106414452?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EOPENSEARCH%7Edefault-9.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EOPENSEARCH%7Edefault-9.control