JavaScript null 与 undefined
JavaScript 是一种强大的语言,但使用不同的数据类型可能会造成混淆,尤其是对于初学者而言。null
和 undefined
数据类型似乎什么都不代表,但它们是不同的。
需要区分这些并知道何时使用哪一个以避免运行时错误。
本文讨论 null
和 undefined
及其区别。
JavaScript 中的 null
null
是 JavaScript 中的一个对象。如果它没有意义,那没关系,因为它是 JavaScript 中的一个错误。它应该是原始数据类型之一,但进行此更改会破坏许多现有的代码库。
这是一个用户分配的值; JavaScript 永远不会单独为变量提供 null
的值。它是分配给留空的变量的值。它可以称为空值。
JavaScript 中的 undefined
undefined
是一种状态。当我们声明一个变量但从未用值初始化它时,它被称为未定义。它是 JavaScript 用来初始化变量的默认值。它也是一个空值。
为什么人们会混淆 null
和 undefined
与 JavaScript 中的相同
null
和 undefined
在以下方面是相同的:
- 两者都是原始数据类型。
- 如果你使用相等运算符
==
比较它们,则返回 true。
null == undefined; // returns true
JavaScript 将两者都视为空值。
- 在表达式中使用时,
undefined
和null
都会产生false
。
!!undefined; // false
!!null; // false
JavaScript 中 null
和 undefined
之间的区别
- 类型差异
console.log(typeof (null)); // object
console.log(typeof (undefined)); // undefined
在上面的示例中,我们使用 typeof
运算符来检查它们的数据类型。它将 null
数据类型作为 object
返回,将 undefined
数据类型返回为 undefined
。尽管相等运算符 ==
返回 true,但标识运算符 ===
将返回 false,因为它们的值相等但具有不同的数据类型。
- 算术运算
null
在执行算术运算时表现得像一个没有值的数字。执行操作会给出类似于 null 为 0
的结果。
console.log(4 + null); // 4
console.log(4 * null); // 0
console.log(4 - null); // 4
console.log(4 / null); // Infinity
需要注意的是,虽然它在算术运算中可能被视为 0
,但 null
的值不是 0
。
同时,undefined
在算术运算中使用时返回 NaN
。
console.log(4 + undefined); // NaN
console.log(4 * undefined); // NaN
console.log(4 - undefined); // NaN
console.log(4 / undefined); // NaN
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。