javascript与unicode排序

And*_*rin 25 javascript sorting

有很多例子可以通过某些属性(即'title')对一些JSON数组进行排序.我们正在使用比较函数,如下所示:

function sortComparer(a, b) {
        if (a.title == b.title)
            return 0;
        return a1 > b1 ? 1 : -1;
    }
Run Code Online (Sandbox Code Playgroud)

问题是塞尔维亚拉丁字母顺序看起来像"A,B,C,Č,Ć,D,......"当使用上面的sortComparer时,我在"Č"或"Ć"之前得到D排序.知道如何对当前的文化语言进行排序吗?

And*_*ris 37

如果系统中的语言环境设置正确,那么您可以使用localeCompare方法而不是大于运算符来比较字符串 - 此方法可识别语言环境.

function sortComparer(a,b){
    return a.title.localeCompare(b.title)
};
Run Code Online (Sandbox Code Playgroud)

  • 这仅在设置了区域设置时才有效.任何将文化与比较价值一起传递的方法? (3认同)
  • 我在这里找到了完整的解决方案http://stackoverflow.com/questions/3630645/how-to-compare-utf-8-strings-in-javascript (3认同)
  • 请注意,`localeCompare`函数比仅使用`<`,`>`和`=`运算符比较字符串要重得多.即使从结果集500开始,使用`localeCompare`也会显着减慢速度.如图所示,它慢了400倍:https://jsfiddle.net/L4715qey/ (3认同)
  • 无法通过脚本设置区域设置,它是由浏览器定义的,或者 - 取决于浏览器 - 从操作系统继承。 (2认同)

Ima*_*our 5

要使用自定义设置对数组进行排序,请执行以下操作:

\n
    \n
  1. 创建一个具有自定义字母顺序的数组:

    \n

    var alphabets = ["A", "B", "C", "\xc4\x8c", "\xc4\x86", "D","D\xc5\xbe","\xc4\x90","E","F","G","H","I","J","K","L","Lj","M","N","Nj","O","P","R","S", "\xc3\x9b\xc5\x92","T","U","V","Z","\xc5\xbd"];

    \n
  2. \n
  3. 创建测试数组列表:

    \n

    var testArrray = ["B2","D6","A1","\xc4\x865","\xc4\x8c4","C3"];

    \n
  4. \n
  5. 创建排序函数名称:

    \n
    function OrderFunc(){\n          testArrray.sort(function (a, b) {\n              return CharCompare(a, b, 0);\n          });\n      }\n
    Run Code Online (Sandbox Code Playgroud)\n
  6. \n
  7. 创建 CharCompare 函数(索引:在“AAAC”之前排序“AAAB”):

    \n
     function CharCompare(a, b, index) {\n  if (index == a.length || index == b.length)\n      return 0;\n  //toUpperCase: isn\'t case sensitive\n  var aChar = alphabets.indexOf(a.toUpperCase().charAt(index));\n  var bChar = alphabets.indexOf(b.toUpperCase().charAt(index));\n  if (aChar != bChar)\n      return aChar - bChar\n  else\n      return CharCompare(a,b,index+1)\n }\n
    Run Code Online (Sandbox Code Playgroud)\n
  8. \n
  9. 调用 OrderFunc 对 testArray 进行排序(结果将是:A1,B2,C3,\xc4\x8c4,\xc4\x865,D6)。

    \n
  10. \n
\n

在线测试

\n

祝你好运

\n