在 JavaScript 中测试两个字符串是否完全匹配的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18588133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to test two strings for exact match in JavaScript
提问by atreju
I want to compare two strings in JavaScriptto test if they are exactlythe same. Which would be the best (fastest) way to do this?
我想比较JavaScript 中的两个字符串以测试它们是否完全相同。哪种方法是最好的(最快的)方法?
Right now, I'm considering either
现在,我正在考虑
if(string1.localeCompare(string2) == 0) {}
or simply
或者干脆
if(string1 == string2)
Is there a better way do to this?
有没有更好的方法来做到这一点?
回答by Andy
I would probably use strict equalityif you want to check they are exactlythe same, ie they're the same typetoo, just in case.
如果你想检查它们是否完全相同,我可能会使用严格相等,即它们也是相同的类型,以防万一。
if (string1 === string2)
回答by Savas Vedova
Check this fiddle* and figure out yourself which one is faster.
检查这个小提琴* 并找出哪个更快。
*In case the link dies in the future: ==
> ===
> String.localeCompare
(tested on Chrome).
*如果链接将来失效:==
> ===
> String.localeCompare
(在 Chrome 上测试)。
回答by kangoroo
if (typeof string1=="string" && typeof string2=="string" && string1 === string2)
no escape method :)
没有逃脱方法:)
回答by Kevin Bowersox
I'm not sure there is any room to optimize if(string1 == string2)
. That is the best approach.
我不确定是否有任何优化空间if(string1 == string2)
。这是最好的方法。