Javascript-关于null、undefined、空字符串的区分

时间:2023-03-09 22:45:29
Javascript-关于null、undefined、空字符串的区分

一.分别判断

 var a=null;
//var a=undefined;
//var a='';
//var a='DD';
if(!a&&typeof a == 'object'){
console.log('a 是null')
}else if(!a&& typeof a == 'undefined'){
console.log('a 是undefined')
}else if(!a&& typeof a == 'string'){
console.log('a 是空字符串')
}else{
console.log('其他')
}

二.项目中可能还有 null、undefined、空字符串与 其他的判断需求

 // var a=null;
// var a=undefined;
//var a='';
var a='DD';
if(!a && (typeof a == 'object'||typeof a =='undefined'||typeof a =='string')){
console.log('a 是null、undefined、空字符串中的一个')
}else{
console.log('其他')
}

三.封装成一个函数供自己使用是不是更好点呢

 function judgeData(str){
if(!str && (typeof str == 'object'||typeof str =='undefined'||typeof str =='string')){
return false;
}else{
return true;
}
}
//通过返回false或true来判断是否是有数据
console.log(judgeData('DD')); //true
console.log(judgeData(null)); //false
console.log(judgeData(undefined)); //false
console.log(judgeData('')); //false