正序
var data = {
"rows": [{
"name": "张三",
"time": "2011/4/1 0:00:00",
},{
"name": "李四",
"time": "2015/5/6 12:30:00",
},{
"name": "王五",
"time": "2012/10/1 22:10:00",
},{
"name": "赵六",
"time": "2011/9/1 22:10:00",
}]
};
var rows = data.rows;
rows.sort(function(a,b){
return Date.parse(a.time) - Date.parse(b.time);//时间正序
});
for(var i =0,l=rows.length;i<l;i++){
console.log(rows[i].name + " | " + rows[i].time);
}
倒序
var data = {
"rows": [{
"name": "张三",
"time": "2011/4/1 0:00:00",
},{
"name": "李四",
"time": "2015/5/6 12:30:00",
},{
"name": "王五",
"time": "2012/10/1 22:10:00",
},{
"name": "赵六",
"time": "2011/9/1 22:10:00",
}]
};
var rows = data.rows;
rows.sort(function(a,b){
return Date.parse(b.time)-Date.parse(a.time);//时间正序
});
for(var i =0,l=rows.length;i<l;i++){
console.log(rows[i].name + " | " + rows[i].time);
}
解释:sort 中a,b表示数组中的任意两个元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b时存在浏览器兼容
var data = {
"rows": [{
"name": "张三",
"time": "2011/4/1 0:00:00",
},{
"name": "李四",
"time": "2015/5/6 12:30:00",
},{
"name": "王五",
"time": "2012/10/1 22:10:00",
},{
"name": "赵六",
"time": "2011/9/1 22:10:00",
}]
};
var rows = data.rows;
rows.sort(function(a,b){
return Date.parse(a.time) - Date.parse(b.time);//时间正序
});
for(var i =0,l=rows.length;i<l;i++){
console.log(rows[i].name + " | " + rows[i].time);
}
倒序
var data = {
"rows": [{
"name": "张三",
"time": "2011/4/1 0:00:00",
},{
"name": "李四",
"time": "2015/5/6 12:30:00",
},{
"name": "王五",
"time": "2012/10/1 22:10:00",
},{
"name": "赵六",
"time": "2011/9/1 22:10:00",
}]
};
var rows = data.rows;
rows.sort(function(a,b){
return Date.parse(b.time)-Date.parse(a.time);//时间正序
});
for(var i =0,l=rows.length;i<l;i++){
console.log(rows[i].name + " | " + rows[i].time);
}
解释:sort 中a,b表示数组中的任意两个元素,若return > 0 b前a后;reutrn < 0 a前b后;a=b时存在浏览器兼容