在 JavaScript 中检查字符串相等性的正确方法是什么?
在 JavaScript 中检查字符串之间是否相等的正确方法是什么?
What is the correct way to check for equality between Strings in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
始终在您完全理解使用==
和===
运算符的差异和含义之前,请使用===
运算符,因为它可以帮助您避免晦涩(不明显)的 bug 和 WTF。由于内部类型强制,“常规”==
运算符可能会产生非常意外的结果,因此始终推荐使用===
方法。为了深入了解这一点以及 Javascript 的其他“好与坏”部分,请阅读 Douglas Crockford 先生和他的作品。有一个很棒的 Google 技术讲座,他总结了很多有用的信息:http://www.youtube.com /watch?v=hQVTIJBZook
更新:
你凯尔·辛普森 (Kyle Simpson) 的《不知道 JS》系列非常出色(并且可以免费在线阅读)。该系列深入探讨了该语言中常见的被误解的领域,并解释了 Crockford 建议您避免的“不好的部分”。通过了解它们,您可以正确使用它们并避免陷阱。
“Up & Going" 书包含关于 平等,具体总结了何时使用宽松 (
==
) 与严格 (===
) 运算符:我仍然向那些不想花时间真正理解 Javascript 的开发人员推荐 Crockford 的演讲——对于偶尔使用 Javascript 的开发人员来说,这是一个很好的建议。
alwaysUntil 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.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
Update:
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.
The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (
==
) vs strict (===
) operators: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.
如果您知道它们是字符串,则无需检查类型。
但请注意,字符串对象不会相等。
将返回 false。
调用 valueOf() 方法将其转换为 String 对象的原始类型,
将返回 true
If you know they are strings, then there's no need to check for type.
However, note that string objects will not be equal.
will return false.
Call the valueOf() method to convert it to a primitive for String objects,
will return true
您可以使用
==
或===
但最后一个以更简单的方式工作(src)a == b (及其否定 !=)
a === b (及其否定 !==)
You can use
==
or===
but last one works in more simple way (src)a == b (and its negation !=)
a === b (and its negation !==)
只是对答案的补充:如果所有这些方法都返回 false,即使字符串看起来相等,也可能在一个字符串的左侧和/或右侧存在空格。因此,只需在比较之前在字符串末尾添加
.trim()
即可:我花了几个小时试图找出问题所在。
希望这对某人有帮助!
Just one addition to answers: If all these methods return false, even if strings seem to be equal, it is possible that there is a whitespace to the left and or right of one string. So, just put a
.trim()
at the end of strings before comparing:I have lost hours trying to figure out what is wrong.
Hope this will help to someone!
导致我提出这个问题的是
padding
和white-spaces
检查我的情况
,标题是
" LastName"
what led me to this question is the
padding
andwhite-spaces
check my case
and title was
" LastName"
实际上有两种方法可以在 javascript 中创建字符串。
var str = 'Javascript';
这将创建一个原始字符串值。var obj = new String('Javascript');
这将创建一个包装对象类型为
字符串
。typeof str // 字符串
typeof obj // object
因此,检查相等性的最佳方法是使用
===
运算符,因为它会检查两个操作数的值和类型。如果您想检查两个对象之间的相等性,那么使用 String.prototype.valueOf 是正确的方法。
There are actually two ways in which strings can be made in javascript.
var str = 'Javascript';
This creates a primitive string value.var obj = new String('Javascript');
This creates a wrapper objectof type
String
.typeof str // string
typeof obj // object
So the best way to check for equality is using the
===
operator because it checks value as well as type of both operands.If you want to check for equality between two objects then using
String.prototype.valueOf
is the correct way.可以使用 JSON.stringify() 技巧检查字符串对象。
String
Objects
can be checked usingJSON.stringify()
trick.严格比较
要进行简单比较,请使用
===
检查严格相等。正如其他人所说,这样做的优点是最有效并减少出现错误或不确定代码的机会。来源:MDN 网络文档:严格平等。按字母顺序比较
如果要根据自然排序比较两个字符串以了解一个字符串是在另一个字符串之前还是之后,请使用
<
、>
、<=
和>=
运算符。来源:MDN WebDocs for<
,>
,
<=
和>=
。Strict Comparisons
To do simple comparison, use
===
to check for strict equality. As others stated, this has the advantages of being most efficient and reducing the chances of buggy or uncertain code. Source: MDN Web Docs: Strict Equality.Alphabetical Comparisons
If you want to compare two strings to know if a string comes before or after another string, based on natural sorting, use the
<
,>
,<=
, and>=
operators. Source: MDN WebDocs for<
,>
,<=
, and>=
.考虑到两个字符串可能都很大,主要有两种方法
按位搜索
和localeCompare
我推荐这个函数
Considering that both strings may be very large, there are 2 main approaches
bitwise search
andlocaleCompare
I recommed this function
对于字符串,我们有一个受支持的方法
localCompare
,它在字符串比较中非常方便。 IMO,我们应该只使用它,不需要使事情复杂化。用法:
For strings, we have a supported method
localCompare
which is very handy in string comparison. IMO, we should just use it and doesn't need to complicate stuff.Usage: