在Javascript中比较字符串的最佳方式? [英] Optimum way to compare strings in Javascript?
问题描述
二进制搜索需要你知道键是否是 ==
枢轴或<
枢轴。
但这需要两个字符串( strcmp()
函数中返回三个值(-1,-1,-1,-1)的函数不同于 C
0,+ 1)for(小于,等于,大于)。
在Javascript中是否有这样一个原生函数,可以返回一个三元值,可以使用 localeCompare()
/ code>方法。
string_a.localeCompare(string_b);
/ *预期回报:
0:完全匹配
-1:string_a< string_b
1:string_a> string_b
* /
进一步阅读:
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.
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).
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?
You can use the localeCompare()
method.
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
Further Reading:
- Stack Overflow - Is there a JavaScript strcmp()?
- Tutorials Point - Javascript String - localeCompare() Method
这篇关于在Javascript中比较字符串的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!