出现以下情况有什么特殊原因吗?
var newVar;
newVar; //returns "undefined"
在以下情况下会变得非常困惑:
newVar == undefined; //true
newVar == null; //true
我读过一些建议使用 typeof 运算符来检测变量是否已声明但已初始化的线程,并且始终使用 null 初始化已声明的变量,但是:
typeof newVar //returns object
虽然我知道(如果我错了,请纠正我)null
是一个对象占位符,因此是一个对象类型,但在 JavaScript 中处理它的方式对我来说真的很困惑.
Web 开发人员的专业 JS 说道:
null
是如何衍生出 undefined
的?
很抱歉提出了很多问题 - 但提前感谢所有答案。
最佳答案
undefined
和 null
之间的关系可能会令人困惑,希望这能澄清它:
首先,它们是值 two different data types :
The Undefined type has exactly one value, called
undefined
. Any variable that has not been assigned a value has the valueundefined
.
(这也解释了为什么变量首先具有值undefined
)和
The Null type has exactly one value, called
null
.
如果您使用严格比较,则更有意义:
null === undefined // false
那么为什么null == undefined
会导致true
呢? Because the specification says so :
2. If x is null and y is undefined, return true.
3. If x is undefined and y is null, return true.
所以,
In what way is
null
a derivative ofundefined
?
事实并非如此。它们是两种不同数据类型的两个不同值。也许从概念上讲,它是某种“衍生品”,但从技术 Angular 来看不是。这本书在这一点上要么过于简单化,要么过于复杂化。
While I'm aware that (correct me if I'm wrong) null is an object placeholder and is thus an object type, the way this is handled in JavaScript is just really confusing for me.
typeof null
返回'object'
,because the specification says so 。这很令人困惑,因为 null
is in actually Null 的数据类型,而不是对象(如最顶部所解释的)。你是对的,也许 null
的最初目的是表示不存在某个对象,但实际上,它可以用来表示不存在任何值。
关于javascript - 将 undefined 赋值给已声明但未初始化的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23048910/