js 判断是否为空

JavaScript020

js 判断是否为空,第1张

js判断是否为空的代码如下:

//  vara=""

//  vara=""

//  vara=null

//  vara=undefined

//  vara=[]

//  vara={}

//  vara=NaN

if(a===undefined){//只能用===运算来测试某个值是否是未定义的

console.log("为undefined")

}

if(a==null){//等同于a===undefined||a===null

console.log("为null")

}

//String

if(a==""||a==null||a==undefined){//"",null,undefined

console.log("为空")

}

if(!a){//"",null,undefined,NaN

console.log("为空")

}

if(!$.trim(a)){//"",null,undefined

console.log("为空")

}

//Array

if(a.length==0){//"",[]

console.log("为空")

}

if(!a.length){//"",[]

console.log("为空")

}

//Object{}

if($.isEmptyObject(a)){//普通对象使用for...in判断,有key即为false

console.log("为空")

}

JavaScript程序是由若干语句组成的,语句是编写程序的指令。JavaScript提供了完整的基本编程语句,它们是:

赋值语句、switch选择语句、while循环语句、for循环语句、foreach循环语句、do...while循环语句、break循环中止语句、continue循环中断语句、with语句、try?catch语句、if语句(if..else,if?elseif?)。

判断一个对象是否为空,介绍如下三种判断方法:

1、直接用for...in...遍历属性,结果为真是“非空数组”,否则是“空数组”,代码如下:

function judgeObj(obj){

for(var a in obj){

return alert('非空对象')

}

return alert('空对象')

}

2、通过JSON自带的.stringify方法来判断,代码如下:

if(JSON.stringify(c)=='{}'){

console.log('空对象')

}

3、ES6新增的方法Object.keys(),代码如下:

if(Object.keys(obj).length==0){

console.log('空对象')

}else{

console.log('非空对象')

}

var a = ""

    if (a =="" ||undefined || null) {

        alert("数据为空")

    }else{

        alert("数据正确")

    }

这样就可以!希望能帮到你~