为什么undefined是一种数据类型

5 javascript null undefined

我最近在调试时学到了,undefined是一种数据类型,null是一个对象.

我认为它们都属于数据类型.

我检查了typeof undefinedtypeof null.他们分别返回"undefined""object".

typeof undefined 
"undefined"

typeof null
"object"
Run Code Online (Sandbox Code Playgroud)

有些人可以解释为什么这种奇怪的行为.

Ben*_*aum 4

typeof null成为对象是一个早期的错误——当他们尝试在 Chrome nightly 中纠正它时typeof null === "null"太多的事情依赖于当前的行为,并且太多的代码被破坏。

未设置为正常值的 JavaScript 对象通常具有三种状态:

  1. 未声明。
  2. 不明确的。
  3. 明确什么都没有。

未申报

例如 - 这种情况:

 y++; //I did not declare y before, this causes a reference error
 y === 'undefined'; //still a reference error 
 typeof y; //'undefined', since typeof is an operator and not a function.
Run Code Online (Sandbox Code Playgroud)

基本上,未声明的变量处于“脚本不知道该变量”的状态。

不明确的

这意味着运行时“知道这个变量”,但尚未设置任何内容。或者,正如语言规范所说:

未定义值 - 当变量尚未分配值时使用的原始值。

例如:

 var y; //y is undefined
 y === undefined; //true, y defined the line above
 typeof y; //undefined, but this is redundant, just do `=== undefined`
 (function(x){ /* x is undefined here as it was set to nothing*/})()
Run Code Online (Sandbox Code Playgroud)

明确没有什么

当你拥有一些应该有价值的东西但你想声明它什么都没有时。或者,正如语言规范所说:

null 值 - 表示故意不存在任何对象值的原始值。

例如,如果具有给定 ID 的元素不在 DOM 中,document.getElementById("foo");则返回以明确指示未返回任何内容。将此与没有 return 语句的函数进行对比,因此它们返回默认值。nullundefined