嵌套的for循环仅执行一次 [英] Nested for-loop only executing once

查看:538
本文介绍了嵌套的for循环仅执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript和jQuery创建一个简单的40x40网格.

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

这是我嵌套的for循环:

Here's my nested for loop to do this:

function display_grid() {
  browser_grid = ''
  $visible_grid = $('#grid');

  for (i = 0; i < 40; i++) {
    $visible_grid.append('<div>');
    for (i = 0; i < 40; i++) {
      $visible_grid.append("<div class='square'> </div>");
    }
    $visible_grid.append('</div>');
  }
}

我希望这将创建40个div,每个内部包含40个div.浏览器仅显示一行具有40个div的行.

I expect this to create 40 divs each with 40 divs inside each one of them. The browser shows only one single row with 40 divs.

<div>
    <div class="square></div>
    <div class="square></div>
    <div class="square></div>
    ...
</div>

这是我想要的,但是四十次.我对JS不太熟悉,所以我对为什么第一个循环没有执行40次感到困惑.

This is what I want it to do, but forty times. I'm not very experienced with JS, so I'm confused as to why the first loop isn't executing 40 times.

推荐答案

内部循环需要一个不同的变量名.

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('<div>');
        for(var j=0; j<40; j++){
            $visible_grid.append("<div class='square'> </div>");
        }
        $visible_grid.append('</div>');
    }

修改:添加了代码. 请注意,您应该使用var关键字在for循环中对变量进行计数.

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

您的代码中发生的事情是,在创建了40个内部div之后,计数器i处于40,并且外部循环的条件不再成立,因此退出了该代码块.

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.

这篇关于嵌套的for循环仅执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆