[英]Why does the outcome change when the variable is declared within the while loop?
I have two simple functions here.我这里有两个简单的功能。 In the loop
function I have defined facky as one at the top of the function. Two things I do not understand:在loop
function 中,我将 facky 定义为 function 顶部的一个。有两件事我不明白:
console.log(loop(5))
is 120 when facky
is defined at the top of loop
当facky
定义在loop
的顶部时, console.log(loop(5))
的答案是 120var facky = 1;
当我移动时var facky = 1;
within the while loop, the answer is 2. I understand why this is two.在 while 循环中,答案是 2。我明白为什么这是两个。 What I don't understand is why the behavior is different when the variable is outside?我不明白的是为什么当变量在外部时行为会有所不同? function loop(size) { while (size > 1) { var facky = 1; facky = facky * size; size = size - 1; } clunk(facky); } function clunk(times) { var num = times; while (num > 0) { console.log("clunk"); num = num - 1; } } loop(5);
In your while loop, whenever the loop iterates, facky
is reset to 1, so it will only print twice because the last iteration of the while loop multiplies facky
by 2.在您的 while 循环中,每当循环迭代时, facky
都会重置为 1,因此它只会打印两次,因为 while 循环的最后一次迭代将facky
乘以 2。
When you move the declaration outside of the while loop, facky
does not reset after every iteration and takes on the value of 5!
当您将声明移到 while 循环之外时, facky
不会在每次迭代后重置并取值5!
, or 120
after the final iteration. ,或最后一次迭代后的120
。
You shouldn't declare a variable inside a loop.您不应该在循环内声明变量。 Try this instead:试试这个:
function loop(size) {
var facky = 1;
while (size > 1) {
facky = facky * size;
size = size - 1;
}
clunk(facky);
}
It doesn't really matter where you declare the var facky
, it's always function-scoped.在哪里声明var facky
重要,它始终是函数范围的。
What matters is whether you reset facky = 1
in every iteration of your loop, or whether you only initialise it once before the loop.重要的是你是否在循环的每次迭代中重置facky = 1
,或者你是否只在循环之前初始化它一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.