JavaScript === vs ==
比较运算符帮助我们确定两个变量是否相等或遵循指定的标准。如果比较结果良好,则返回 true
;否则,它返回 false
。本教程解释了比较运算符中最令人困惑的话题,并教授何时使用哪个等于运算符(==
或 ===
)。
单等号 =
与双等号 ==
和三等号 ===
完全不同,因为它是一个赋值操作,它们是比较运算符。因此,混淆通常在 ==
和 ===
之间。
JavaScript 中的松散相等运算符 (==
)
==
运算符或相等运算符也称为抽象比较运算符。之所以称为抽象,是因为它只关心变量的值而不关心变量的类型。==
运算符在将变量值相互比较之前将它们转换为相同的类型(类型强制),如果转换的操作数相等,则返回 true。由于运算符必须执行类型转换,因此它往往比 ===
运算符慢一点。
现在,要了解何时使用哪个运算符,我们首先必须了解一些有关类型强制的知识。它有两种类型:
- 显式强制转换: 使用内置方法通过代码显式完成。例如:要将字符串
"42"
转换为数字,我们必须编写Number("42")
。这样,我们使用显式的Number()
类型转换方法将字符串转换为数字。 - 隐式强制转换: 它是由语言隐式完成的。它通常在我们将两种不同类型的操作数与运算符一起使用时执行。例如:如果我们执行
1 + ""
。有一个数字和一个字符串不能直接相加,所以 JavaScript 类型将数字转换为字符串,因为这是它们相加的唯一方式,并返回一个字符串"1"
。
23 == '23' // returns true
true + false == 1 // returns true
undefined ==
null // returns true
[] == 0 // returns true
JavaScript 中的严格相等运算符 (===
)
===
运算符或恒等运算符也称为严格比较运算符。之所以称为严格,是因为它只有在两个操作数的类型和值都相同时才返回真。它不执行任何类型的转换;因此,它往往比 ==
运算符更快。
true === true // returns true
true === 1 // returns false
因此,选择 ==
或 ===
运算符的决定取决于类型强制。如果不熟悉类型强制,那么他应该坚持使用严格相等运算符。
相关文章
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 事件。