Nested for-loop only executing once

前端 未结 2 1619
后悔当初
后悔当初 2021-01-28 08:26

I am using JavaScript and jQuery to create a simple 40x40 grid.

Here\'s my nested for loop to do this:

function display_grid() {
  browser_grid = \'\'
           


        
2条回答
  •  忘了有多久
    2021-01-28 09:05

    You need a different variable name for the inner loop.

    function display_grid() {
        browser_grid='';
        $visible_grid = $('#grid');
    
        for(var i=0; i<40; i++){
            $visible_grid.append('
    '); for(var j=0; j<40; j++){ $visible_grid.append("
    "); } $visible_grid.append('
    '); }

    Edit: Added code. Note that you should use the var keyword for counting variables in your for-loops.

    What happened in your code is that after the 40 inner divs are created, the counter i is at 40 and the condition for the outer loop isn't true any longer, thus exiting that code block.

提交回复
热议问题