本文翻译自:Optimum way to compare strings in JavaScript? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- Is there a JavaScript strcmp()? 有没有JavaScript strcmp()? 5 answers 5个答案
I am trying to optimize a function which does binary search of strings in JavaScript. 我正在尝试优化一个在JavaScript中对字符串进行二进制搜索的函数。
Binary search requires you to know whether the key is ==
the pivot or <
the pivot. 二进制搜索要求您知道密钥是==
枢轴还是<
枢轴。
But this requires two string comparisons in JavaScript, unlike in C
like languages which have the strcmp()
function that returns three values (-1, 0, +1)
for (less than, equal, greater than). 但这需要在JavaScript中进行两次字符串比较,这与C
语言类似,后者的strcmp()
函数返回三个值(-1, 0, +1)
(小于,等于,大于)。
Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search? JavaScript中是否存在这样的本机函数,它可以返回三元值,以便在二进制搜索的每次迭代中只需要进行一次比较?
#1楼
参考:https://stackoom.com/question/95tK/在JavaScript中比较字符串的最佳方法-重复
#2楼
You can use the localeCompare()
method. 您可以使用localeCompare()
方法。
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
Further Reading: 进一步阅读:
- MDN: String.prototype.localeCompare MDN:String.prototype.localeCompare
- Stack Overflow - Is there a JavaScript strcmp()? Stack Overflow - 是否有JavaScript strcmp()?
- Tutorials Point: JavaScript String - localeCompare() Method 教程要点:JavaScript字符串 - localeCompare()方法
#3楼
You can use the comparison operators to compare strings . 您可以使用比较运算符来比较字符串 。 A strcmp
function could be defined like this: strcmp
函数可以像这样定义:
function strcmp(a, b) {
if (a.toString() < b.toString()) return -1;
if (a.toString() > b.toString()) return 1;
return 0;
}
Edit Here's a string comparison function that takes at most min { length( a ), length( b ) } comparisons to tell how two strings relate to each other: 编辑这是一个字符串比较函数,它最多需要min {length( a ),length( b )}比较,以告诉两个字符串如何相互关联:
function strcmp(a, b) {
a = a.toString(), b = b.toString();
for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
if (i === n) return 0;
return a.charAt(i) > b.charAt(i) ? -1 : 1;
}
#4楼
Well in JavaScript you can check two strings for values same as integers so yo can do this: 在JavaScript中你可以检查两个字符串的值与整数相同,所以你可以这样做:
-
"A" < "B"
-
"A" == "B"
-
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp()
. 因此,您可以创建自己的函数,以与strcmp()
相同的方式检查字符串。
So this would be the function that does the same: 所以这将是相同的功能:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}