js中undefined和null判断

判断是否为undefined

var exp = undefined;
if (typeof(exp) == undefined)
{
    
    
    alert("undefined");
}

判断是否为null

var exp = null; 
if (!exp && typeof(exp)!=”undefined” && exp!=0) 
{
    
     
alert(“is null); 
} 

判断对象为空

var data = {
    
    };
var arr = Object.keys(data);
alert(arr.length == 0);//true

判断数组为空

let arr = [];
if (arr.length == 0){
    
    
   console.log("数组为空")
}else {
    
    
   console.log("数组不为空")
}

判断数组是否含有某个值

if (arr.indexOf(2) != -1){
    
    
   console.log("数组含有2")
}else {
    
    
   console.log("数组不含2")
}

参考来源:JS 中判断空值 undefined 和 null

猜你喜欢

转载自blog.csdn.net/qq_34307801/article/details/104005516