undefined,null,NaN的区别

  • null的类型是个一对象,代表一个空值。
  • undefined的类型是一个对象,代表没有定义。
  • NaN的类型是一个number,代表不是数值类型。

1. null

把一个变量的值设置为null,就表示该变量的值不是有效的对象,数组,数字,字符串和布尔值。null对应类型Object,布尔值false,数字0,字符串“null”

    var test = null;
    //类型,输出object
    document.write( typeof (test));
    document.write("<br/>");
 
    //字符串,输出nulltest
    document.write(test + 'test');
    document.write("<br/>");
 
    //数字,输出10
    document.write(test + 10);
    document.write("<br/>");
 
    //布尔值,输出false
    if (test) {
       document.write("true");
    }
    if (!test) {
     document.write("false");
    }

2. undefined

当你使用一个未被声明的变量时或者已经声明了但还没有赋值,又或者使用了一个不存在的对象属性,返回的就是undefined。undefined对应类型undefined,布尔型false,字符串undefined,数字计算结果一定是NaN

    var test; 
 
    //类型,输出undefined
    document.write( typeof (test));
    document.write("<br/>");
 
    //字符串,输出undefinedtest
    document.write(test + 'test');
    document.write("<br/>");
 
    //数字,输出NaN
    document.write(test + 10);
    document.write("<br/>");
 
    //布尔值,输出false
    if (test) {
     document.write("true");
    }
    if (!test) {
       document.write("false");
    }

3. NaN

NaN 属性代表一个“不是数字”的值。这个特殊的值是因为运算不能执行而导致的,不能执行的原因要么是因为其中的运算对象之一非数字(例如, "abc" / 4),要么是因为运算的结果非数字(例如,除数为零)。判断一个变量是否为NaN。ES6提供了一个新的 Number.isNaN() 函数,这是一个不同的函数,并且比老的全局 isNaN() 函数更可靠。

    // 两大惊人特性
    // 1 这的是Number型的
    console.log(typeof NaN === "number");  // logs "true"

    // 2 自己和自己并不相等
    console.log(NaN === NaN);  // logs "false"

4. null和undefined的比较

    null == undefined 返回true

    null===undefined  返回false
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容