undefined和null

记录一些出现undefiend和null的情况:

undefined是全局对象的一个属性,它是全局作用域的一个变量。undefined的最初值就是原始数据类型undefined。

出现undefined的情况:
  1. 变量预解析阶段只声明未赋值,变量默认值为undefined
  2. 函数定义没有返回值,或return后面什么也没有,函数默认返回值为undefined
  3. 函数定义形参不传值,参数默认就是undefined。
  4. 访问对象的属性,对象没有该属性名,则属性值默认undefined。
  5. 严格模式(”use strict”),没有明确的主体,this指的就是undefined而不是window。

null 只是一个字面量(而不是全局对象的一个属性,undefined 是)。在 APIs 中,null 常被放在期望一个对象,但是不引用任何对象的参数位置。当检测 null 或 undefined 时,注意相等(==)与全等(===)两个操作符的区别 (前者会执行类型转换)。

出现undefined的情况:
  1. 手动设置变量的值或者对象某一个属性值为null(此时不赋值,会在后面的代码中进行赋值,相当于初始化。)
  2. 在JS的DOM元素获取中,如果没有获取到指定的元素对象,结果一般是null。
  3. Object.prototype.proto的值也是null
  4. 在正则捕获的时候,如果没有捕获到结果,默认也是null。
补充:undefiened与null的不同点
typeof null        // object (因为一些以前的原因而不是'null')
typeof undefined   // undefined
null === undefined // false
null  == undefined // true
null === null // true
null == null // true
!null //true
isNaN(1 + null) // false
isNaN(1 + undefined) // true

ps:目前只遇到这么多,遇到新的再更新,更多的欢迎评论补充~

你可能感兴趣的:(undefined和null)