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

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

问题描述

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

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

推荐答案

始终 直到您完全理解使用 == === 的差异和含义运算符,使用 === 运算符,因为它可以避免模糊(非明显)的错误和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先生及其作品。有一个很棒的Google Tech Talk,他总结了很多好消息: 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

更新:

你不了解JS Kyle Simpson的系列作品非常出色(可以免费在线阅读)。该系列进入了语言中常被误解的领域,并解释了克罗克福德建议你避免的坏部分。通过了解它们,你可以正确使用它们并避免陷阱。

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 book included关于平等的一节,有关何时使用松散( == )vs strict( === )运营商:

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:


  • 如果比较中的任何一个值(也就是边)可能是 true false 值,避免 == 并使用 ===

  • 如果比较中的任何一个值可能是这些sp ecific值( 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天全站免登陆