排序日/月阵列在Javascript [英] Sort day/month array in Javascript

查看:116
本文介绍了排序日/月阵列在Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想整理日期从最新到最旧的阵列,可惜list.sort(默认),仅排序第一号。我的数组是这样的:

I'm trying to sort an Array of dates from latest to oldest, and unfortunately list.sort (by default) only sorts the first number. My array looks like this:

var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"];

我试图使为的.sort以参考作用,但整个过程有点混乱给我。任何人都可以帮我吗?

I tried to make a function for the .sort to reference, but the whole process is somewhat confusing to me. Could anyone help me out?

推荐答案

您将不得不字符串解析成的日期()的对象,如果不是因为IE的这将是足够直截了当执行不力日期字符串解析。幸运的是,你可以使用的的setDate()的和的 setMonth()的有跨浏览器的一致性,无论是接受号码 - 为1-31的的setDate()的,对于0-11的 setMonth()的。设置当月名对象映射会有所帮助。

You'll have to parse the strings into Date() objects, which would be straightforward enough if it weren't for IE's poor implementation of date string parsing. Fortunately, you can use setDate() and setMonth() with consistency across browsers, both accept numbers - 1-31 for setDate(), 0-11 for setMonth(). Setting up an object map for the month names will help.

这对我的作品:

(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"]

我已经设置了一个例子 - http://jsfiddle.net/Tw6xt/

这篇关于排序日/月阵列在Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆