Can't wrap my head around why this piece of JavaScript code outputs 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. Since the outer loop runs 10
times as well, the inner loop runs 10 x 10
times, which is 100
.
Consider one iteration of the inner loop. It runs 10
times, right? Since num
is 0
initially, after the inner loop runs the first time, num
will be 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
. This means that you eventually end up with num
equal to 100
.
Try running this, you can watch the behavior of i
, j
, and num
:
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)
Because you have nested for loops. So the the inner 10 will execute 10 times. 10^2 = 100.
It does the inner loop 10 times.
for (var j=0; j < 10; j++) {
num++; // 10
}
Then it does it 10 more times because it's in a for loop.
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. 10 times every time it is called. It's called 10 times. 10 * 10 = 100.
For loops loop x times.
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. The inner loop executes 10 times. The inner loop execution add 1 to num; 10*10 of adding 1 yields 100
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.