在Javascript中比较字符串的最佳方式? [英] Optimum way to compare strings in Javascript?

查看:190
本文介绍了在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:

这篇关于在Javascript中比较字符串的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆