我最近在调试时了解到,undefined是一种数据类型,null是一个对象。
我认为它们都属于数据类型。
我检查了typeof undefined和typeof null。他们分别返回“未定义”和“对象”。
typeof undefined
"undefined"
typeof null
"object"
有人可以解释为什么这是奇怪的行为。
typeof null
成为对象是一个早期的错误-当他们每晚晚上在Chrome中尝试对其进行更正时,typeof null === "null"
太多的事情依赖于当前的行为,并且有太多的代码中断了。
未设置为正常值的JavaScript对象通常具有三种状态:
例如-这种情况:
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.
基本上,未声明的变量处于“脚本不知道该变量”状态。
这意味着运行时“知道此变量”,但尚未将其设置为任何值。或者,如语言规范所述:
未定义值-未为变量分配值时使用的原始值。
例如:
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*/})()
当您拥有应该具有值的东西但想要声明它什么都不是时。或者,如语言规范所述:
空值-表示故意不存在任何对象值的原始值。
例如,document.getElementById("foo");
返回null
如果给定ID的元素不在DOM指示明确没有返回。将其与没有return语句的函数进行比较,以使它们返回undefined
默认值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句