阻止工作时如何? [英] How does this while block work?

查看:77
本文介绍了阻止工作时如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

console.log(result);

我很困惑这里的计数器更新结果如何?我们正在增加1,但这会对结果产生什么影响?

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. :)

[已解决]

与for循环相同的代码。

Same code with for loop.

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


推荐答案

结果计数器是此代码中具有不同目标的单独变量。

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

counter 增加,如

 counter += 1

因此最终条件

while (counter<10)

将被满足并且代码将停止执​​行。

will be satisfied and the code will cease to execute.

至于结果,每次执行while块中的代码时,结果乘以2更新

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

result = result*2

由于变量 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.

这篇关于阻止工作时如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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