問題:
This question already has an answer here: 這個問題在這裏已有答案:
- Is there a JavaScript strcmp()? 有沒有JavaScript strcmp()? 5 answers 5個答案
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中是否存在這樣的本機函數,它可以返回三元值,以便在二進制搜索的每次迭代中只需要進行一次比較?
解決方案:
參考一: https://stackoom.com/question/95tK參考二: Optimum way to compare strings in JavaScript? [duplicate]