我使用jQuery处理一小时时间集的数组,例如:
{hours[0] = '12a-1a',
hours[1] = '1a-2a',
hours[2] = '2a-3a',
hours[3] = '2p-3p',
hours[4] = '9p-10p',
hours[5] = '10p-11p'}
想知道是否有人知道如何从上述数组中的连续小时数范围中提取开始和结束时间,例如:
范围1:12a-3a
范围2:2p-3p
范围3:9p-11p
最终目标是我想向用户显示汇总范围,如下所示:
您选择了:12a-3a和2p-3p以及9p-11p
到目前为止,我知道如何显示用户选择的唯一方法是显示小时数组中的每个系列。在大型集合上,这最终会在屏幕上显示太多。
任何帮助将不胜感激!
答案 0 :(得分:2)
由于数据采用自定义字符串格式,因此您需要执行以下操作:
var hours = [];
hours[0] = '12a-1a', hours[1] = '1a-2a', hours[2] = '2a-3a', hours[3] = '2p-3p', hours[4] = '9p-10p', hours[5] = '10p-11p';
// Convert a time like 1p-2p etc to an hour value pair
function convertToValue(hours) {
// convert midnight to hour 0
hours = hours.replace(/12a/, '0a');
var parts = hours.split('-');
var start = parseInt(parts[0]);
if (parts[0].match(/p/)) {
start += 12;
}
var end = parseInt(parts[1]);
if (parts[1].match(/p/)) {
end += 12;
}
return {
start: start,
end: end
};
}
// Return a number in the range 0-23 as a string 12am, 11pm etc
function formatTime(time) {
if (!time) {
return "12a";
} else if (time == 12) {
return "12p";
} else if (time > 12) {
return (time - 12) + "p";
}
return time + "a";
}
// Convert an entry with start and end time to a formatted time like 1p-3p
function formattedTime(item) {
return formatTime(item.start) + '-' + formatTime(item.end);
}
// Collect the converted results
var results = [];
$.each(hours, function(i, hours) {
results.push(convertToValue(hours));
});
// Merge any adjacent times together
var merged = [];
$.each(results, function(i, result) {
// If not first entry, see if this entry extends the previous entry
if (i && result.start == results[i - 1].end) {
// Extend the previous entry
merged[merged.length - 1].end = result.end;
} else {
merged.push(result);
}
});
// Save the new formatted output
var output = [];
$.each(merged, function(i, time) {
output.push(formattedTime(time));
})
// Combine with "and" to get final result
console.log(output.join(" and "));
导致输出结果:
12a-2a and 2p-3p and 9p-10p