JavaScript空假值及其判断

一、javaScript五种空值和假值

分别为undefined,null,false,"",0,这五个值的共同点是在执行if语句时都会执行false分支,执行对应的非语句的时候都执行true分支。

1、undefined:表明变量没有初始化,即“未定义”;

2、null:js关键字,用于描述“空值”,表示数字、字符串、对象是“无值”的,typeof为object,但不具备对象实例的属性与方法;

3、false、""、0:在if语句中表现为假值,但是他们都是有意义的数据,只是被用作空值或假值;

数据类型如下:

typeof(undefined) == 'undefined'
typeof(null) == 'object'
typeof("") == 'String'
typeof(0) == 'number'
typeof(false) == 'boolean'

二、数据是否为空的判断

//    var a = "";
//    var a = " ";
//    var a = null;
//    var a = undefined;
//    var a = [];
//    var a = {};
//    var a = 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("为空");
    }

 

posted @ 2019-05-17 14:32  Dreamsqin  阅读(2209)  评论(0编辑  收藏  举报