简体   繁体   English

另一个for循环内的for循环

[英]For loop inside another for loop

Can't wrap my head around why this piece of JavaScript code outputs 100. 我无法理解为什么这段JavaScript代码会输出100。

var num = 0;

for (var i=0; i < 10; i++) {
    for (var j=0; j < 10; j++) {
        num++;
    }
}

alert(num); // 100

The inner loop runs 10 times for every iteration of the outer loop. 对于外循环的每次迭代,内循环运行10次。 Since the outer loop runs 10 times as well, the inner loop runs 10 x 10 times, which is 100 . 由于外循环也运行10次,因此内循环运行10 x 10次,即100

Consider one iteration of the inner loop. 考虑内循环的一次迭代。 It runs 10 times, right? 它运行了10次,对不对? Since num is 0 initially, after the inner loop runs the first time, num will be 10 . 由于最初num0 ,因此在内循环首次运行后, num将为10 I mentioned earlier that the inner loop runs 10 times for each iteration of the outer loop, so after each iteration of the outer loop, num is basically incremented by 10 . 我之前提到过,内循环对于外循环的每次迭代运行10次,因此在外循环的每次迭代之后, num基本上增加10 This means that you eventually end up with num equal to 100 . 这意味着您最终将得到num等于100

Try running this, you can watch the behavior of i , j , and num : 尝试运行此命令,您可以观察ijnum的行为:

var num = 0;
for (var i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
        alert("i = "+i+", j = "+j+", num = "+num);
        num++;
    }
}
alert(num);

i iterates 10 times, j iterates to 10 i times, and so num is incremented 100 times (10 * 10) i迭代10次, j迭代10次i ,因此num递增100次(10 * 10)

Because you have nested for loops. 因为您嵌套了循环。 So the the inner 10 will execute 10 times. 因此内部10将执行10次。 10^2 = 100. 10 ^ 2 = 100。

It does the inner loop 10 times. 它执行内循环10次。

    for (var j=0; j < 10; j++) {
        num++; // 10
    }

Then it does it 10 more times because it's in a for loop. 然后再执行10次,因为它处于for循环中。

for (var i=0; i < 10; i++) {
   // each time this runs you will add 10.
}

In the end the inner for loop will run 100 times. 最后,内部for循环将运行100次。 10 times every time it is called. 每次调用10次。 It's called 10 times. 这叫十次。 10 * 10 = 100. 10 * 10 = 100。

For loops loop x times. For循环循环x次。

var count = 0;
for(var i = 0; i < 10; i++)
    count++;
//count = 10

So Sequential loops ADD 所以顺序循环添加

var count = 0;
for(var i = 0; i < 7; i++)
    count++;
for(var i = 0; i < 10; i++)
    count++;
//count = 17 // 7 (first) + 10 (second)

But loops Within loops MULTIPLY (because each INNER loop is executed for each OUTER loop) 但是循环内循环成倍增加(因为每个内部循环都针对每个外部循环执行)

var count = 0;
for(var i = 0; i < 4; i++)
    for(var i = 0; i < 10; i++)
        count++;
//count = 40 // 4 (outer) * 10 (inner)

So to calculate loop iterations multiply inner by outer, or for sequential add the first then the second 因此,要计算循环迭代,请将内部乘以外部,或顺序地将第一个然后第二个相加

The inner loop is executed 10 times. 内部循环执行10次。 The inner loop executes 10 times. 内部循环执行10次。 The inner loop execution add 1 to num; 内部循环执行将1加到num; 10*10 of adding 1 yields 100 10 * 10加1得到100

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

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