javascript 使用 unicode 进行排序 [英] javascript sort with unicode

查看:38
本文介绍了javascript 使用 unicode 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多示例可以按某些属性(即标题")对一些 JSON 数组进行排序我们正在使用这样的比较函数:

There are a lot of examples for sorting some JSON array by some property (i.e. 'title') We are using compare function like this one:

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

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

Problem is that Serbian Latin alphabet order looks like "A, B, C, Č, Ć, D,..." When using sortComparer above I am getting D sorted before "Č" or "Ć". Any idea how to sort respecting current culture language?

推荐答案

如果您系统中的区域设置正确,那么您可以使用 localeCompare 方法代替 greater-than 运算符来比较字符串 - 此方法是区域设置感知的.

If the locale in your system is set correctly then you can use localeCompare method instead of greater-than operator to compare the strings - this method is locale aware.

function sortComparer(a,b){
    return a.title.localeCompare(b.title)
};

这篇关于javascript 使用 unicode 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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