Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中比较字符串的最佳方法? [重复](Optimum way to compare strings in JavaScript? [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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

  ask by HRJ translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(进一步阅读:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...