在JavaScript中对天数数组进行排序 [英] Sort array of days in javascript

查看:105
本文介绍了在JavaScript中对天数数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组.该数组可以包含1到7个唯一的日期名称字符串.日期名称将按从星期一到星期日的顺序排列. -例如:

I have an array. The array can contain 1 to 7 unique strings of day names. The day names will be in order from Mon to Sun. - eg:

["Tue","Thu","Sun"]

["Tue", "Thu", "Sun"]

我想使用javascript对数组进行排序,以便从今天开始订购.

I want to use javascript to sort that array so that the order will be beginning with today.

ie:如果今天是星期五,则排序后的数组应为

ie: if today is Friday, then the sorted array should be

[太阳",星期二",星期四"]

["Sun", "Tue", "Thu"]

如果今天是星期四,则排序后的数组应为

if today is Thursday then the sorted array should be

[星期四",星期日",星期二"]

["Thu", "Sun", "Tue"]

任何人都可以帮忙吗?

推荐答案

function sort_days(days) {

要获取今天的星期几,请使用new Date().getDay().假设Sunday = 0, Monday = 1, ..., Saturday = 6.

To get today's day of week, use new Date().getDay(). This assumes Sunday = 0, Monday = 1, ..., Saturday = 6.

    var day_of_week = new Date().getDay();

要生成星期几的列表,然后切片名称列表:

To generate the list of the days of week, then slice the list of names:

    var list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    var sorted_list = list.slice(day_of_week).concat(list.slice(0,day_of_week));

(今天是星期五,所以sorted_list['Fri','Sat','Sun','Mon','Tue','Wed','Thu'])

(today is Friday, so sorted_list is ['Fri','Sat','Sun','Mon','Tue','Wed','Thu'])

最后,要排序,请使用indexOf:

Finally, to sort, use indexOf:

    return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}

将它们放在一起:

function sort_days(days) {
    var day_of_week = new Date().getDay();
    var list = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    var sorted_list = list.slice(day_of_week).concat(list.slice(0,day_of_week));
    return days.sort(function(a,b) { return sorted_list.indexOf(a) > sorted_list.indexOf(b); });
}

这篇关于在JavaScript中对天数数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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