What is the correct way to check for string equality in JavaScript?
什么是正确的方法来检查JavaScript之间的字符串平等?
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.
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:
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
or false
value, avoid ==
and use ===
. 0
, ""
, or []
-- empty array), avoid ==
and use ===
. ==
. Not only is it safe, but in many cases it simplifies your code in a way that improves readability. 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.
If you know they are strings, then there's no need to check for type.
"a" == "b"
However, note that string objects will not be equal.
new String("a") == new String("a")
will return false.
Call the valueOf() method to convert it to a primitive for String objects,
new String("a").valueOf() == new String("a").valueOf()
will return true
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:
if(s1.trim() === s2.trim())
{
// your code
}
I have lost hours trying to figure out what is wrong. Hope this will help to someone!
链接地址: http://www.djcxy.com/p/19384.html