javascript - 将 undefined 赋值给已声明但未初始化的变量?

标签 javascript null undefined

出现以下情况有什么特殊原因吗?

var newVar;
newVar; //returns "undefined"

在以下情况下会变得非常困惑:

newVar == undefined; //true
newVar == null; //true

我读过一些建议使用 typeof 运算符来检测变量是否已声明但已初始化的线程,并且始终使用 null 初始化已声明的变量,但是:

typeof newVar //returns object

虽然我知道(如果我错了,请纠正我)null 是一个对象占位符,因此是一个对象类型,但在 JavaScript 中处理它的方式对我来说真的很困惑.

Web 开发人员的专业 JS 说道: null == undefined

null 是如何衍生出 undefined 的?

很抱歉提出了很多问题 - 但提前感谢所有答案。

最佳答案

undefinednull 之间的关系可能会令人困惑,希望这能澄清它:

首先,它们是值 two different data types :

The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

(这也解释了为什么变量首先具有值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 of undefined?

事实并非如此。它们是两种不同数据类型的两个不同值。也许从概念上讲,它是某种“衍生品”,但从技术 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/

相关文章:

java - 尝试解析数组时出现空指针异常(java)

c# - 如何在 C# 中解析未知的日期时间格式

javascript - 如何围绕特定点旋转几何图形?

python - pd.notnull 奇怪的 null 检查行为

c# - 为什么一个null返回可以被测试而另一个会抛出异常?

javascript - Node JS)未定义的图像上传问题

javascript - 您将如何在 ejs 中为 node.js 检查未定义的属性?

javascript - 在 Ember.js 中实现 Accordion 式 View

javascript - 从 Angular 4 HTTP 调用获取完整响应(不仅仅是正文)

javascript - 生成 ENOENT 错误 - NodeJS