我没有得到我期望的排序结果。怎么了?
以下是代码:
data.sort(function(a,b){
return (Date.parse(a) - Date.parse(b));
});
for(var j = 0; j < data.length; j++){
var item = data[j];
console.log(j+") " +item.createdAt+":"+Date.parse(item.createdAt));
}
这是输出:
0) Fri Jun 10 2016 16:58:26 GMT-0400 (Eastern Daylight Time):1465592306000
1) Tue Jun 07 2016 08:07:34 GMT-0400 (Eastern Daylight Time):1465301254000
2) Fri Jun 10 2016 15:57:44 GMT-0400 (Eastern Daylight Time):1465588664000
3) Fri Jun 10 2016 14:34:45 GMT-0400 (Eastern Daylight Time):1465583685000
4) Fri Jun 10 2016 14:22:02 GMT-0400 (Eastern Daylight Time):1465582922000
5) Fri Jun 10 2016 11:14:34 GMT-0400 (Eastern Daylight Time):1465571674000
6) Fri Jun 10 2016 10:03:56 GMT-0400 (Eastern Daylight Time):1465567436000
7) Fri Jun 10 2016 10:02:58 GMT-0400 (Eastern Daylight Time):1465567378000
8) Thu Jun 09 2016 16:32:29 GMT-0400 (Eastern Daylight Time):1465504349000
9) Thu Jun 09 2016 16:29:24 GMT-0400 (Eastern Daylight Time):1465504164000
答案 0 :(得分:1)
由于data
是对象的数组,并且每个对象都包含要对其进行排序的createdAt
属性,因此需要
data.sort(function(a, b) {
return (Date.parse(a.createdAt) - Date.parse(b.createdAt));
});
如果数据来自服务器数据库,我建议在数据库本身的日期对数据进行排序。
答案 1 :(得分:0)
Tushar击中它的头部,如果那是你想要的东西。如果您想进一步深入了解特定值比较的排序,您将要研究数组原型。你可以在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
找到