在 JavaScript 中比较字符串的最佳方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2167602/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:03:28  来源:igfitidea点击:

Optimum way to compare strings in JavaScript?

javascriptstringoptimizationcomparisonbinary-search

提问by HRJ

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 Clike 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 中是否有这样一个本机函数,它可以返回一个三元值,以便在二进制搜索的每次迭代中只需要进行一次比较?

回答by Daniel Vassallo

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:

进一步阅读:

回答by Cipi

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"
  • "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));  
}

回答by Gumbo

You can use the comparison operators to compare strings. A strcmpfunction 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:

编辑????这里的一个字符串比较函数,它至多分钟{长度(),长度(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;
}