显然你不应该这样做,因为排序更有意义,然后反转结果,但如果你真的想在 sort 函数中以相反的顺序排序,你可以做这样的事情......
_.sortBy(["Bob", "Mary", "Alice"], function (a) {
// split each string into single characters
// ... then swap for inverse character from unicode range
// ... and glue the characters back together into an inversely sortable string
return _.map(a.split(''), function(i){
return String.fromCharCode(65536 - i.charCodeAt(0));
}).join('');
});
...还值得注意的是,下划线与原生 javascript 排序略有不同,后者在一致的排序顺序方面存在一个小的跨平台问题...
如果 compareFunction(a, b) 返回 0,则 a 和 b 保持不变,但对所有不同的元素进行排序。注意:ECMAscript 标准不保证这种行为,因此并非所有浏览器(例如,至少可以追溯到 2003 年的 Mozilla 版本)都尊重这一点。 Array.prototype.sort()
Underscore 的 .sortBy 文档指出:
返回列表的(稳定)排序副本。 _.sortBy
它不是返回0 来保持项目有序,而是返回左侧的索引减去右侧的索引。
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};