简体   繁体   中英

Javascript: for-loop not working

I have this code right here.. where the variable num is the dimension of an by n square table. The objective is to enter a number and create a table with the number as the dimension.

I got this code but it doesn't go through the 2 layers of for-loops. After the code execution, the string *change_text* just becomes: <table></table>

    change_text = "<table>";

    for (var i; i<num; i++) {
        change_text = change_text + "<tr>";
        for (var j; j<num; j++) {
            change_text = change_text + "<td> asdf </td>";

            //code for blue cells
        }
        change_text = change_text + "</tr>";
    }


    change_text = change_text+ "</table>"

您需要初始化您的迭代器:

for(var i = 0; i < num; i++)

You need to specify the starting value for your loops:

change_text = "<table>";

    for (var i = 0; i<num; i++) {
        change_text = change_text + "<tr>";
        for (var j = 0; j<num; j++) {
            change_text = change_text + "<td> asdf </td>";

            //code for blue cells
        }
        change_text = change_text + "</tr>";
    }


    change_text = change_text+ "</table>"

At present I would assume i and j are undefined and so the loops won't go anywhere.

you need to initialize i and j... try this:

change_text = "<table>";

for (var i=0; i<num; i++) {
    change_text = change_text + "<tr>";
    for (var j=0; j<num; j++) {
        change_text = change_text + "<td> asdf </td>";

        //code for blue cells
    }
    change_text = change_text + "</tr>";
}


change_text = change_text+ "</table>"

您需要初始化 i 和 j,如下所示:

for (var i = 0; i<num; i++)

Not initialized i,make i=0

 for (var i=0; i<num; i++) {
       //code
    }

Ohhh also I noticed that num isn't defined specifically. Wherever you're getting num from make sure to use parseInt if it could have possibly been passed as a string. num = parseInt(num);

You forgot the i=0 / j=0 initialisation. You only declared the variables, and undefined always yields false from numeric comparisons which breaks the loop immediately. So change your code to

change_text = "<table>";
for (var i=0; i<num; i++) {
    change_text = change_text + "<tr>";
    for (var j=0; j<num; j++) {
        change_text = change_text + "<td> asdf </td>";
        //code for blue cells
    }
    change_text = change_text + "</tr>";
}
change_text = change_text+ "</table>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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