Different result between localCompare and comparison operator for special characters in JavaScript

前端 未结 1 2002
北荒
北荒 2021-01-22 04:51

While looking at one issue related to sorting, I came across interesting difference for non alpha numeric characters comparison between string localeCompare method

相关标签:
1条回答
  • 2021-01-22 05:08

    Why different response for special characters in different browsers?

    Probably because as it says in the ECMA-402 (internationalization) spec:

    Subsets of Unicode: Some operations, such as collation, operate on strings that can include characters from the entire Unicode character set. However, both the Unicode standard and the ECMAScript standard allow implementations to limit their functionality to subsets of the Unicode character set. In addition, locale conventions typically don’t specify the desired behaviour for the entire Unicode character set, but only for those characters that are relevant for the locale. While the Unicode Collation Algorithm combines a default collation order for the entire Unicode character set with the ability to tailor for local conventions, subsets and tailorings still result in differences in behaviour.

    Most likely, the order of @ vs. _ just isn't significantly defined in the locales you're using (or mine; UK English), and so you get "differences in behavior."

    What is correct way to implement this? (Check data type; if string use localeCompare else conditional operator?)

    Yes. > and < use the numeric relationship of the code points in the Unicode standard, which isn't really a very good way to handle collation at all, while localeCompare provides a locale-specific collation to characters.

    To be clear: When you say you "...used conditional operator", I assume you mean the conditional operator (? :) combined with a relational operator (> or < in this case), e.g. something like:

    return a === b ? 0 : a > b ? 1 : -1;
    

    ...or similar in a sort callback.

    But note that since you're now using localeCompare for strings, and the only other thing you can really meaningfully compare with > and < is numbers, there's a better solution for numbers if you know none of them is NaN: Just subtract:

    return a - b; // For numbers that aren't NaN
    

    (If either of them may be NaN, you'll want to handle that — perhaps with the conditional operator. :-) )

    0 讨论(0)
提交回复
热议问题