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

一.分别判断

 1 var a=null;
 2 //var a=undefined;
 3 //var a='';
 4 //var a='DD';
 5 if(!a&&typeof a == 'object'){
 6     console.log('a 是null')
 7 }else if(!a&& typeof a == 'undefined'){
 8     console.log('a 是undefined')
 9 }else if(!a&& typeof a == 'string'){
10     console.log('a 是空字符串')
11 }else{
12     console.log('其他')
13 }

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

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

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

 1 function judgeData(str){
 2     if(!str && (typeof str == 'object'||typeof str =='undefined'||typeof str =='string')){
 3         return false;
 4     }else{
 5         return true;
 6     }
 7 }
 8 //通过返回false或true来判断是否是有数据
 9 console.log(judgeData('DD')); //true
10 console.log(judgeData(null)); //false
11 console.log(judgeData(undefined)); //false
12 console.log(judgeData('')); //false
原文地址:https://www.cnblogs.com/studyshufei/p/8464272.html