per*_*ine 10 javascript sorting lodash
我想知道为什么lodash不会以字符串格式排序日期数组与普通javascript相比sort().这是预期的行为还是一个错误?
array = ["2014-11-11", "2014-11-12", null, "2014-11-01", null, null, "2014-11-05"]
_.sortBy(array);
// ["2014-11-11", "2014-11-12", null, "2014-11-01", null, null, "2014-11-05"]
_.sortBy(array, function(value) {return new Date(value);});
// [null, null, null, "2014-11-01", "2014-11-05", "2014-11-11", "2014-11-12"]
array.sort()
// ["2014-11-01", "2014-11-05", "2014-11-11", "2014-11-12", null, null, null]
Run Code Online (Sandbox Code Playgroud)
使用的版本:Lo-Dash v2.4.1 - 现代版本.
Kir*_*ril 24
如果您查看lodash代码,您可能会看到它是如何实现的._.sortBy里面的函数使用native Array.prototype.sort(参见source).但根本不在那里.更有趣的是compareAscending作为回调传递给native sort(source)的函数.所以说几句话
_.sortBy(array, function(value) {return new Date(value);});
转换为:
array.sort(function(a, b) {
var aa = new Date(a),
bb = new Date(b);
if (aa !== bb) {
if (aa > bb) { return 1; }
if (aa < bb) { return -1; }
}
return aa - bb;
})
Run Code Online (Sandbox Code Playgroud)
那么为什么nulls一开始呢?因为new Date(null)返回Thu Jan 01 1970 01:00:00值小于数组中的任何其他日期.
原生sort呢?根据规范(参见此处)默认排序顺序是根据字符串Unicode代码点.如果简单 - native sort将项目转换为字符串并比较字符串.所以原生排序就像:
_.sortBy(array, function(value) {return value + ''; });
Run Code Online (Sandbox Code Playgroud)
一旦'null'字符串总是比日期字符串"更大"(如'2014-11-11') - nulls将位于结果数组的尾部.