我有一系列的日子
[0,1,4,5,6]
这些天我如何让这些天以这样的格式打印
"周日-周一,周四-周六">
var hours = {
firstSet: {
days: [0,1,4,5,6]
},
secondSet: {
days: [1,4,6]
}
};
var prevDay = null;
var counter = 0;
function loadHours() {
$.each(hours,function(id,val){
prevDay = null;
counter = 0;
var dayString = "";
$.each(val.days, function(day){
counter += 1;
if (counter == 1) {
dayString += checkDayString(prevDay, day);
} else if (counter == val.days.length) {
dayString += "-"+getDayName(day);
}
});
});
}
function checkDayString(prevDay, day) {
if (prevDay == null) {
prevDay = day;
return getDayName(day);
}
}
function getDayName(day) {
switch(day) {
case 0:
return "Sun";
break;
case 1:
return "Mon";
break;
case 2:
return "Tue";
break;
case 3:
return "Wed";
break;
case 4:
return "Thu";
break;
case 5:
return "Fri";
break;
case 6:
return "Sat";
break;
}
}
您可以使用reduce
对数组中出现的连续日期进行分组,然后使用map
使用数字组的第一个和最后一个索引将其转换为单词范围。
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var ranges = [0, 1, 4, 5, 6];
var words = ranges
.reduce((acc, curr) => {
if (acc.length === 0) {
acc.push([curr]);
return acc;
}
let r = acc[acc.length - 1];
if (curr - r[r.length - 1] === 1) r.push(curr);
else acc.push([curr]);
return acc;
}, [])
.map(range => range.length === 1 ?
days[range[0]] :
days[range[0]] + "-" + days[range[range.length - 1]])
console.log(words.join(', '));