How does this while block work? [closed]

回眸只為那壹抹淺笑 提交于 2019-12-01 13:40:44

问题


var result = 1
var counter = 0
while (counter < 10) {
     result = result * 2
     counter += 1
};

console.log(result);

I am confused how does counter update result here? We are increasing counter by 1 but how does that affect the result?

Can someone please dumb it down to me? I am new to programming.

Edit : I know this question has been asked many times. I searched through many answers but didn't get the info I required. I have a very specific doubt and wanted to clarify it so please go easy on that down button. :)

[Solved]

Same code with for loop.

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

回答1:


result and counter are separate variables with different goals in this code.

counter is incremented like

 counter += 1

so that eventually the while condition

while (counter<10)

will be satisfied and the code will cease to execute.

As for result, each time the code in the while block is executed, result updated by multiplying by 2

result = result*2

It is 'updated' because the variable result was initialized outside the while loop but is accessible by it. With the above statement, it is taking the existing result variable and multiplying it by 2 then storing it back in result.




回答2:


You mean this:

loop | counter |  result  | counter < 10
  1       1          2           yes
  2       2          4           yes
  3       3          8           yes
  4       4          16          yes
  5       5          32          yes
  6       6          64          yes
  7       7          128         yes
  8       8          256         yes
  9       9          512         yes
  10      10         1024        no end of loop


  console.log(result);   ->    1024


来源:https://stackoverflow.com/questions/30267753/how-does-this-while-block-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!