简体   繁体   English

为什么这会导致无限循环?

[英]Why does this result in an endless loop?

The code is meant to generate an calendar using javascript and tables. 该代码旨在使用javascript和表生成日历。 The months and days are in dutch but it should be understandable. 几个月和几天是荷兰语,但这应该是可以理解的。 Somehow this end in an endless loop while it should stop when days is bigger or the same as the length of my array. 不知何故,这会以无限循环结束,而当天数大于或等于我的数组长度时,它应该停止。

It's supposed to make 12 tables for each month and then fill these up with the days of that month. 它应该每个月制作12个表,然后用那个月的日子填满它们。 It's not finished yet since it'll presume that every day will start at sunday. 它还没有完成,因为它会假设每天都会在星期天开始。 I think I should also note that I'm not that experienced yet. 我想我也应该注意到,我还没那么有经验。

var months = new Array();
months[0] = "januari";
months[1] = "februari";
months[2] = "maart";
months[3] = "april";
months[4] = "mei";
months[5] = "juni";
months[6] = "juli";
months[7] = "augustus";
months[8] = "september";
months[9] = "oktober";
months[10] = "november";
months[11] = "december";

var maxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var weekDays = ["zo", "ma", "di", "wo", "do", "vr", "za"];
var kalender = 0;
var days = 1;
var weekDaysNumber = 0;


while(kalender < months.length){
    document.write("<table><tr>");
    document.write("<th>" + months[kalender] + "</th></tr>");
    document.write("<tr>");
    while (weekDaysNumber < 7){
        document.write("<td>" + weekDays + "</td>";
        weekDaysNumber++;
    }
    document.write("</tr>");
    while(days < maxDays[kalender]){
        document.write("<td>" + days + "</td>");

        var rows = 0;
        if(rows == 7 && days !== maxDays[kalender]){
        document.write("</tr>");
        document.write("<tr>");
        rows = 1;
        }

        rows++;
        days++;

    }

    if(days == maxDays[kalender]){
            document.write("</tr></table>");
            kalender++;
            weekDaysNumber=0;

        }

}

Because you never reset the days variable to 1 , and so on the second outer loop, it's never equal to maxDays[kalendar] . 因为你永远不会将days变量重置为1 ,所以在第二个外循环中,它永远不会等于maxDays[kalendar] There may well be other issues, the code looks much more complex than necessary, but that's the glaring reason for the infinite loop: When days reaches 31 , you break the first loop, start the second, and since 31 is greater than 28 the inner loop is never entered and your == maxDays[kalendar] is never entered. 可能还有其他问题,代码看起来比必要复杂得多,但这是无限循环的明显原因:当天days达到31 ,你打破第一个循环,开始第二个循环,并且因为31大于28 ,内部永远不会输入循环,并且永远不会输入== maxDays[kalendar]


Your browser has a fully-featured debugger built into it. 您的浏览器内置了功能齐全的调试器。 You can use that to set breakpoints, single-step through code, inspect variables, etc. 您可以使用它来设置断点,单步执行代码,检查变量等。

您需要在while(kalender < months.length){循环while(kalender < months.length){ days重置为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM