美文网首页
undefined,null,NaN的区别

undefined,null,NaN的区别

作者: 程序员潜规则 | 来源:发表于2019-12-27 01:25 被阅读0次
  • 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

相关文章

网友评论

      本文标题:undefined,null,NaN的区别

      本文链接:https://www.haomeiwen.com/subject/wgrroctx.html