在 JavaScript 中检查字符串相等性的正确方法是什么? [英] What is the correct way to check for string equality in JavaScript?

查看:20
本文介绍了在 JavaScript 中检查字符串相等性的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中检查字符串是否相等的正确方法是什么?

What is the correct way to check for equality between Strings in JavaScript?

推荐答案

always 直到您完全理解使用 ===== 运算符,请使用 === 运算符,因为它可以使您免于晦涩(不明显)的错误和 WTF.常规" == 运算符可能会由于内部的类型强制转换而产生非常意外的结果,因此始终推荐使用 === 方法.

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

要深入了解这一点,以及 Javascript 的其他好与坏"部分,请阅读 Douglas Crockford 先生和他的作品.有一个很棒的谷歌技术演讲,他总结了很多很好的信息:http://www.youtube.com/watch?v=hQVTIJBZook

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook

更新:

Kyle Simpson 的 你不知道 JS 系列非常出色(并免费在线阅读).该系列深入探讨了语言中普遍被误解的领域,并解释了 Crockford 建议您避免的坏部分".通过了解它们,您可以正确使用它们并避免陷阱.

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

Up & Going" 一书包含关于 Equality,以及何时使用松散(==) 与严格 (===) 运算符:

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

将大量细节归结为几个简单的要点,并帮助您了解在各种情况下是使用 == 还是 ====,这里是我的简单规则:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • 如果比较中的任一值(也称为边)可能是 truefalse 值,请避免 == 并使用 ===.
  • 如果比较中的任一值可能是这些特定值(0""[] -- 空数组),避免 == 并使用 ===.
  • 所有其他情况下,您可以安全地使用 ==.它不仅安全,而且在许多情况下,它以提高可读性的方式简化了您的代码.
  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

对于不想花时间真正理解 Javascript 的开发者,我仍然推荐 Crockford 的演讲——对于偶尔使用 Javascript 的开发者来说,这是一个很好的建议.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

这篇关于在 JavaScript 中检查字符串相等性的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆