在JavaScript中对天数数组进行排序 [英] Sort array of days in 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屋!