这个while块是如何工作的? [英] How does this while block work?
问题描述
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
和 counter
在此代码中是具有不同目标的独立变量.
result
and counter
are separate variables with different goals in this code.
counter
像
counter += 1
所以最终 while
条件
while (counter<10)
将得到满足,代码将停止执行.
will be satisfied and the code will cease to execute.
对于result
,每次执行while块中的代码,result
乘以2更新
As for result
, each time the code in the while block is executed, result
updated by multiplying by 2
result = result*2
它是更新的",因为变量 result
是在 while
循环之外初始化的,但可以被它访问.使用上述语句,它将现有的 result
变量乘以 2,然后将其存储回 result
.
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
.
这篇关于这个while块是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!