在Javascript中对日/月数组进行排序

1 javascript arrays sorting

我正在尝试对从最新到最旧的日期数组进行排序,不幸的是list.sort(默认情况下)只对第一个数字进行排序.我的数组看起来像这样:

var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"];
Run Code Online (Sandbox Code Playgroud)

我试图为.sort创建一个函数来引用,但整个过程对我来说有点混乱.任何人都可以帮我吗?

And*_*y E 5

您必须将字符串解析为Date()对象,如果不是IE的日期字符串解析的不良实现,这将是非常简单的.幸运的是,您可以使用setDate()setMonth()在浏览器中保持一致性,两者都接受数字 - 对于setDate()为1-31 ,对于setMonth()为0-11 .为月份名称设置对象图将有所帮助.

这对我有用:

(function () { 
    // Set up our variables, 2 date objects and a map of month names/numbers
    var ad = new Date(),
        bd = new Date(),
        months = {
            Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
            Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov:10, Dec:12
        };

    MyArray.sort(function (a,b) {
        // Split the text into [ date, month ]
        var as = a.split(' '),
            bs = b.split(' ');

        // Set the Date() objects to the dates of the items
        ad.setDate(as[0]);
        ad.setMonth(months[as[1]]);
        bd.setDate(bs[0]);
        bd.setMonth(months[bs[1]]);

        /* A math operation converts a Date object to a number, so 
           it's enough to just return date1 - date2 */
        return ad - bd;
    });
})();
//-> ["09 Jun", "13 Jun", "30 Jun", "13 Aug", "25 Aug"]
Run Code Online (Sandbox Code Playgroud)

我为你建立了一个例子 - http://jsfiddle.net/Tw6xt/