在JavaScript中检查字符串是否相等的正确方法是什么?
当前回答
考虑到这两个字符串可能都非常大,有两种主要的方法按位搜索和localeCompare
我推荐这个函数
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
其他回答
在您完全理解使用==和===操作符的区别和含义之前,请使用===操作符,因为它将避免您出现模糊的(不明显的)错误和wtf。由于内部的类型强制,“常规”==操作符可能会产生非常意想不到的结果,因此始终推荐使用===方法。
要深入了解这一点,以及Javascript的其他“好与坏”部分,请阅读Douglas Crockford先生和他的作品。有一个很棒的谷歌技术谈话,他总结了很多好的信息:http://www.youtube.com/watch?v=hQVTIJBZook
更新:
Kyle Simpson的《You Don’t Know JS》系列非常棒(可以在网上免费阅读)。本系列文章探讨了英语中常被误解的部分,并解释了Crockford建议你避免的“不好的部分”。通过理解它们,你可以正确地使用它们,避免陷阱。
“Up & Going”一书中有一节是关于相等的,具体总结了什么时候使用宽松(==)和严格(===)操作符:
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: 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的开发人员来说,这是一个很好的建议。
考虑到这两个字符串可能都非常大,有两种主要的方法按位搜索和localeCompare
我推荐这个函数
function compareLargeStrings(a,b){
if (a.length !== b.length) {
return false;
}
return a.localeCompare(b) === 0;
}
你可以使用==或===,但最后一个更简单(src)
A == b(和它的否定!=)
A === b(和它的否定!==)
让我想到这个问题的是填充和空白
检查我的箱子
if (title === "LastName")
doSomething();
标题是"姓"
也许你需要像这样使用修剪函数
var title = $(this).text().trim();
还要考虑["foo", "bar"] == "foo,bar"。