如何重载比较器以使用 UTF-8 和不同的语言环境进行排序
How to overload comparator to sort with UTF-8 and different locales
我有一组数据:
["Alphabet","Zend","Ćwiczenia"]
作为结果 collection.sort
我得到:["Alphabet","Zend","Ćwiczenia"]
.
如何重载 comparator
以使用 UTF-8 和不同的语言环境进行排序?
您需要设置一个comparator method on your collection that uses localeCompare
作为它的排序功能。
假设你的collection看起来像
var c = new C([
{name: "Alphabet"},
{name: "Zend"},
{name: "Ćwiczenia"}
]);
看起来像
var C = Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('name').localeCompare(b.get('name'));
}
});
和一个演示
var C = Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('name').localeCompare(b.get('name'));
}
});
var c = new C([
{name: "Alphabet"},
{name: "Zend"},
{name: "Ćwiczenia"}
]);
console.log(c.pluck('name'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
我有一组数据:
["Alphabet","Zend","Ćwiczenia"]
作为结果 collection.sort
我得到:["Alphabet","Zend","Ćwiczenia"]
.
如何重载 comparator
以使用 UTF-8 和不同的语言环境进行排序?
您需要设置一个comparator method on your collection that uses localeCompare
作为它的排序功能。
假设你的collection看起来像
var c = new C([
{name: "Alphabet"},
{name: "Zend"},
{name: "Ćwiczenia"}
]);
看起来像
var C = Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('name').localeCompare(b.get('name'));
}
});
和一个演示
var C = Backbone.Collection.extend({
comparator: function(a, b) {
return a.get('name').localeCompare(b.get('name'));
}
});
var c = new C([
{name: "Alphabet"},
{name: "Zend"},
{name: "Ćwiczenia"}
]);
console.log(c.pluck('name'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>