本书未发布

undefined 和 null 的异同

未匹配的标注
  • 相同点

    1. 两种数据类型都只有一个字面值, 即 undefinednull

    2. 两种数据类型在转换成布尔类型的时候, 都会转换成 false, 所以在通过 ! 来取反的时候, 没有办法判断到底是 undefined 还是 false

    3. 当将两者转换成对象的时候, 都会抛出一个 TypeError 的异常, 如下:

      let a;
      let b = null;
      
      console.log(a.name); // Cannot read property 'name' of undefined
      console.log(b.name); // Cannot read property 'name' of null
    4. 在非严格情况下, undefined 和 null 是相等的

      true == undefined; // true

  • 不同点:

    1. null 是JavaScript 中的关键字, 而 undefined 是一个全局变量, 就是挂载在 Window 对象中的一个变量, 不是关键字
    2. 在使用 typeof() 检测数据类型的时候, undefined 返回的是 undefined, null 返回的是 object
    3. 在通过 call 调用 toString() 函数时, undefined 类型的值会返回 [object Undefined], null 类型会返回 [object Null]
      Object.prototype.toString().call(undefined); // [object Undefined]
      Object.prototype.toString().call(null); // [object Null]
    4. 在进行字符串类型转换的时候, null 会转换成字符串的 ‘null’, undefined 会转换成字符串的 ‘undefined’
    5. 在进行数值计算的时候, undefined 会转换成 NaN, 无法参与计算; null 会转换成 0, 可以参与计算
    6. 无论在什么情况下, 都没有必要将一个变量显示的设置成 undefined. 如果需要定义一个变量来存将来要使用的对象, 那么应该将其初始化为 null

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~