[英]Why can't I declare a variable inside a for loop?
Why can't I declare a variable inside a for loop below? 为什么不能在下面的for循环中声明变量?
Wrong: 错误:
for(let i = 1; i <= num; i++){
let factorials = [];
if(num % i === 0){
factorials.push(i);
}
}
// ReferenceError: factorials is not defined
Correct: 正确:
let factorials = [];
for(let i = 1; i <= num; i++){
if(num % i === 0){
factorials.push(i);
}
}
If you define a variable inside of { }
. 如果您在
{ }
内定义变量。 It means that the variable is only alive inside of the { }
. 这意味着该变量仅在
{ }
内部有效。 It's called a scope. 这称为范围。
You have a scope using if/while/for/function
... 您可以使用
if/while/for/function
...
In the following example, the factorials
variable is alive only inside of one loop iteration of the for
. 在以下示例中,
factorials
变量仅在for
的一个循环迭代内for
。 Which means that you are recreating a factorials
variable every time you loop. 这意味着您每次循环都在重新创建
factorials
变量。
for(let i = 1; i <= num; i++){
const factorials = [];
if(num % i === 0){
factorials.push(i);
}
}
If you want to make it work, you have to create your variable outside of the for so it will not be recreate after every iteration, and keep it's values. 如果要使其生效,则必须在for之外创建变量,这样它将不会在每次迭代后重新创建并保持其值。
const factorials = [];
for(let i = 1; i <= num; i++){
if(num % i === 0){
factorials.push(i);
}
}
In the first code snippet, you are declaring factorials
inside the for loop block, hence it will not be visible outside the for loop block. 在第一个代码段中,您是在for循环块内声明
factorials
,因此在for循环块外将不可见。
It is working in the 2nd snippet because you declared it outside of block. 它在第二个代码段中起作用,因为您在代码块之外声明了它。
Why can't I declare a variable inside a for loop below?
为什么不能在下面的for循环中声明变量?
No, you can. 不,可以。
Here is the proof. 这是证明。
let num = 5; for (let i = 1; i <= num; i++) { let factorials = []; if (num % i === 0) { factorials.push(i); } } let factorials = []; for (let i = 1; i <= num; i++) { if (num % i === 0) { factorials.push(i); } } console.log("No Error.")
Yes, you can, but if you declare the factorials-array in the loop it's only available in that closure. 是的,可以,但是如果在循环中声明阶乘数组,则仅在该闭包中可用。 So consoling it out of the loop won't work.
因此,将其从循环中删除将不起作用。
Here's a very informative article about closures: https://javascript.info/closure 这是有关闭包的非常有用的文章: https : //javascript.info/closure
The whole javascript.info-site is very interesting, I am studying it for now to strengthen my javascript basics and fill not known informations-holes, although I am into web developing since years. 整个javascript.info网站都非常有趣,尽管我多年来从事网络开发工作,但我现在仍在研究它以增强我的javascript基础并填补未知的信息漏洞。 But it never hurts to get more knowledge, even if its the basics.
但是,即使是基础知识,获取更多知识也不会有任何伤害。
Also I would advice you to use "use strict;" 我也建议您使用“严格使用”; from beginning when developing, it helps to keep your scripts more clean, disallowing sources of errors.
从开发开始就可以帮助您保持脚本的整洁,避免出现错误源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.