在 JavaScript 中比较字符串的最佳方法? [英] Optimum way to compare strings in JavaScript?
问题描述
我正在尝试优化一个在 JavaScript 中对字符串进行二进制搜索的函数.
I am trying to optimize a function which does binary search of strings in JavaScript.
二分查找要求你知道键是==
主元还是<
主元.
Binary search requires you to know whether the key is ==
the pivot or <
the pivot.
但这需要在 JavaScript 中进行两次字符串比较,不像在 C
中那样具有 strcmp()
函数的语言返回三个值 (-1, 0, +1)
表示(小于、等于、大于).
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 中是否有这样一个原生函数,它可以返回一个三元值,以便在二分查找的每次迭代中只需要进行一次比较?
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?
推荐答案
您可以使用 localeCompare()
方法.
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
进一步阅读:
- MDN:String.prototype.localeCompare
- 堆栈溢出 - 是否有 JavaScript strcmp()?
- 教程要点:JavaScript 字符串 - localeCompare() 方法
这篇关于在 JavaScript 中比较字符串的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!