简体   繁体   English

谁能告诉我 for 循环中发生了什么

[英]Can anyone tell me what happens in for loop

Here is the code that computes 2 10 , using for loop : How did the 1024 answer come?这是使用 for 循环计算 2 10 的代码: 1024 答案是怎么来的?

var result = 1;
for ( var counter = 0; counter < 10; counter = counter + 1)
result = result * 2;
console . log ( result );
//  1024

Basically基本上

1024 = 2 10 1024 = 2 10

(2 * 2 ... 10 times) (2 * 2 ... 10 次)

The for loop loops 10 times, each time result is multiplied by 2 (was 1 initially). for循环循环 10 次,每次结果乘以 2(最初为 1)。

Indenting you code gives缩进你的代码给出

var result = 1;

for ( var counter = 0; counter < 10; counter = counter + 1)
    result = result * 2;

console . log ( result );  // display result in console

Since you don't have a block ( {} ) around the for loop statements, only the first statement is in the loop ( result = result * 2; ), so it's multiplying the result with 2, 10 times, ie由于 for 循环语句周围没有块( {} ),因此循环中只有第一条语句( result = result * 2; ),因此它将结果乘以 2, 10 次,即

result = 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2

and after that you are outputing that result ( 1024 ).之后,您将输出该结果( 1024 )。

Your for loop only runs result = result * 2 .您的for loop只运行result = result * 2

Now, your result initial value is 1 .现在,您的result初始值为1 Then this will do the operation of result * 2 for 10 times which gives the result of 1024然后这将执行result * 2的操作 10 次,结果为1024

2
4
8
16
32
64
128
256
512
1024
for (statement 1; statement 2; statement 3) {
    code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.语句 1 在循环(代码块)开始之前执行。

Statement 2 defines the condition for running the loop (the code block).语句 2 定义了运行循环(代码块)的条件。

Statement 3 is executed each time after the loop (the code block) has been executed.每次执行循环(代码块)后都会执行语句 3。

In your case, this loop runs 10 times.在您的情况下,此循环运行 10 次。 In your "statement 1", you assign counter to 0.Then, you define the condition, which is that the for loop will run until counter is = or > 10 (so until the condition isn't met).在您的“语句 1”中,您将计数器分配给 0。然后,您定义条件,即 for 循环将运行直到计数器 = 或 > 10(因此直到不满足条件)。 On "statement 3" you are just adding one to counter at the end of every loop.在“语句 3”中,您只是在每个循环结束时向计数器添加一个。

Therefore, you are multiplying variable "result" (which is assigned a value of 1) times 2, 10 times .因此,您将变量“result”(赋值为 1)乘以 2, 10 次 After that, the console.log just prints the result variable.之后,console.log 只打印结果变量。

//2^10 = 1024

hope this helps, here's a link to for loop syntax: http://www.w3schools.com/js/js_loop_for.asp希望这会有所帮助,这是 for 循环语法的链接: http : //www.w3schools.com/js/js_loop_for.asp

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

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