何时在 JavaScript 中使用 === 运算符检查?

发布于 2024-09-02 04:14:03 字数 464 浏览 1 评论 0原文

可能的重复:
Javascript === 与 == :哪个重要我使用“等于”运算符?

正如标题所述;使用 JavaScript 时何时应该使用 === 运算符检查,何时不应该使用。

编辑:在此处找到了更完整的答案。感谢马克·拜尔斯指出这一点。

_L

Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?

As the title states; when should you use the === operator check when using JavaScript, and when not to.

Edit: more complete answer found here. Thanks to Mark Byers for pointing it out.

_L

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

久而酒知 2024-09-09 04:14:03

它是严格类型相等运算符。它不仅检查两个是否相等,而且类型相同。

考虑比较数字或字符串时的情况:

if (4 === 4) // same value and type
{
  // true
}

but

if (4 == "4") // same value and different type but == used
{
  // true
}

and

if (4 === "4") // same value but different type
{
  // false
}

这适用于对象和数组。

因此,在上述情况下,您必须做出明智的选择,是使用 == 还是 ===

使用 === 是个好主意当你也确定类型时

It is strict type equality operator. It not only checks whether two are equal in value but also of the same type.

Consider a situation when you compare numbers or strings:

if (4 === 4) // same value and type
{
  // true
}

but

if (4 == "4") // same value and different type but == used
{
  // true
}

and

if (4 === "4") // same value but different type
{
  // false
}

This applies to objects as well as arrays.

So in above cases, you have to make sensible choice whether to use == or ===

It is good idea to use === when you are sure about the type as well

沙与沫 2024-09-09 04:14:03

当您希望禁止隐式类型转换时。例如:

3 == '3'

true,而这不是:

3 === '3'

Douglas Crockford 建议始终使用严格比较。

When you wish to inhibit implied typecasts. For example:

3 == '3'

is true, whereas this is not:

3 === '3'

Douglas Crockford recommends always using strict comparison.

溺渁∝ 2024-09-09 04:14:03

您可以使用它来检查变量的包含值和类型是否与比较变量相同。

You use it to check if a variable's containing value and type is same as the compared one.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文