区分JS中的undefined,null,"",0和false

来源:互联网 发布:免费的数据恢复app 编辑:程序博客网 时间:2024/05/20 10:23
typeof(undefined) == 'undefined' typeof(null) == 'object' typeof("") == 'string' typeof(0) == 'number' typeof(false) == 'boolean'

undefined和null比较特殊,虽然null的类型是object,但是null不具有任何对象的特性,就是说我们并不能执行null.toString()、null.constructor等对象实例的默认调用。所以从这个意义上来说,null和undefined有最大的相似性。看看null == undefined的结果(true)也就更加能说明这点。不过相似归相似,还是有区别的,就是和数字运算时,10 + null结果为:10;10 + undefined结果为:NaN。

    var a=null;    if (typeof  a=="object" && a==undefined){        console.log(' var a=null;typeof  a=="object" && a==undefined');    }        var b=null;    if (b==undefined && b==null){        console.log(' var b=null ; b==undefined && b==null');    }    b=undefined;    if (b==undefined && b==null){        console.log(' b=undefined; b==undefined && b==null');    }

    另外""、0和false虽然在if语句表现为"假值",可它们都是有意义数据,只是被作为了"空值"或"假值",因为:"".toString(),(0).toString()和false.toString()都是合法的可执行表达式。

0 0
原创粉丝点击