• 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("为空");
        }
  • 相关阅读:
    源码安装extundelete以及对遇到问题的解决
    centos 连不上网
    memcache 永久数据被踢
    svn 分支
    HTML5 中已经可以用 Ajax 上传文件了,而且代码非常简单,借助 FormData 类即可发送文件数据。
    sublime安装DocBlockr注释插件
    rsync 无密码 传输
    滚动条滑到底部,加载更多
    svn 同步脚本
    蒲公英[分块]
  • 原文地址:https://www.cnblogs.com/dreamsqin/p/10881181.html
Copyright © 2020-2023  润新知