如果我有对象列表:
var objectList= LIST_OF_OBJECT;列表中的每个对象包含三个属性:"名称","日期","性别 "
each object in the list contains three attributes: "name", "date","gender"
如何按"日期"属性的升序对列表中的对象进行排序?
How to sort the objects in the list by "date" attribute ascending order?
("日期"属性包含类似于"2002-08-29 21:15:31 + 0500"的字符串值)
(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")
推荐答案Array.sort 方法接受一个sort函数,该函数接受两个元素作为参数,并应返回:
The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:
- <如果第一个小于第二个,则为0
- 如果第一个等于第二个,则为0
- >如果第一个大于第二个,则为0.
.
objectList.sort(function (a, b) { var key1 = a.date; var key2 = b.date; if (key1 < key2) { return -1; } else if (key1 == key2) { return 0; } else { return 1; } });您很幸运,在您提供的日期格式中,另一个日期之前的日期也比使用字符串比较时的日期还要<.如果不是这种情况,则必须先将字符串转换为日期:
You're lucky that, in the date format you've provided, a date that is before another date is also < than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:
objectList.sort(function (a, b) { var key1 = new Date(a.date); var key2 = new Date(b.date); if (key1 < key2) { return -1; } else if (key1 == key2) { return 0; } else { return 1; } });更多推荐
如何按日期升序对对象进行排序?
发布评论