我正在創建一個項目,我想通過我的day_schedule()
創建一個名爲full_day[]
的數組,其長度與數組time_plan[]
完全相等。在JavaScript中嵌套循環條件
這裏是我的代碼:
function day_schedule(){
var time_plan = [{"lesson_start":"08:00","lesson_end":"09:00"},{"lesson_start":"09:00","lesson_end":"10:00"},{"lesson_start":"10:00","lesson_end":"11:00"},{"lesson_start":"11:00","lesson_end":"12:00"},{"lesson_start":"12:00","lesson_end":"13:00"},{"lesson_start":"13:00","lesson_end":"13:30"},{"lesson_start":"13:30","lesson_end":"14:30"}];
var day = [{"subject_name":"Math-1","lesson_start":"08:00","lesson_end":"09:00"},{"subject_name":"Phy","lesson_start":"11:00","lesson_end":"12:00"},{"subject_name":"Engl","lesson_start":"12:00","lesson_end":"13:00"}];
var key1 = 'lesson_start';
var key2 = 'lesson_end';
var full_day = [];
for (var d = 0; d < day.length; d++) {
var start_time = day[d].lesson_start;
var end_time = day[d].lesson_end;
for (var i = 0; i < time_plan.length; i++) {
var search_key = time_plan[i][key1] == start_time && time_plan[i][key2] == end_time;
if (search_key == true) {
document.writeln('day matched == ' + day[d],'<br>');
full_day.push(day[d]);
} else {
full_day.push({
lesson_start: ' ',
lesson_end: ' ',
subject_name: ' '
});
}
}
console.log('full day',full_day.length, full_day);
}
}
day_schedule();
我期待的
full day 7 [
{
"subject_name": "Math-1",
"lesson_start": "08:00",
"lesson_end": "09:00"
},
{
"lesson_start": " ",
"lesson_end": " ",
"subject_name": " "
},
{
"lesson_start": " ",
"lesson_end": " ",
"subject_name": " "
},
{
"subject_name": "Phy",
"lesson_start": "11:00",
"lesson_end": "12:00"
},
{
"subject_name": "Engl",
"lesson_start": "12:00",
"lesson_end": "13:00"
},
{
"lesson_start": " ",
"lesson_end": " ",
"subject_name": " "
},
{
"lesson_start": " ",
"lesson_end": " ",
"subject_name": " "
}
];
結果,但我不能弄清楚如何做到這一點。
我需要的是full_day陣列爲等於長度time_plan陣列(在這種情況下應該是7長度)通過插入空/恆定目的是full_day []當沒有發現匹配,而[]比較time_plan與天[ ]。 – sh2ka