简体   繁体   English

在全局范围内使用“let”创建的变量与在循环内使用“var”创建的变量

[英]variable created with “let” in global scope vs variable created with “var” inside a loop

I am trying to get some experience with the variable declarations in JavaScript. 我试图获得JavaScript中的变量声明的一些经验。 in the following code, whenever I try to define the variable inside the loop with var keyword it throws me an error: 在下面的代码中,每当我尝试使用var关键字在循环内定义变量时,它会抛出一个错误:

"Uncaught SyntaxError: Identifier 'i' has already been declared". “未捕获的SyntaxError:标识符'i'已经被声明”。

whereas if I use "let" keyword (or no keyword at all) there is no problem. 而如果我使用“let”关键字(或根本没有关键字),则没有问题。 I know that in the case that I don't use any keyword, JavaScript uses the same variable in the global scope and overwrites it. 我知道在我不使用任何关键字的情况下,JavaScript在全局范围内使用相同的变量并覆盖它。 I also know that variables created with "let" keyword are considered block scope and variables created with "var" keyword outside a function are considered global. 我也知道用“let”关键字创建的变量被认为是块范围,在函数外部用“var”关键字创建的变量被认为是全局变量。 but I don't understand this behavior! 但我不明白这种行为! I would be grateful if anybody could shed illumination on this matter. 如果有人能够对这个问题有所了解,我将不胜感激。

this code: 这段代码:

let i = 78;
console.log(i);
for (var i = 0; i < 4; i++) {
    console.log(i);
    var insideloop = 100;
}

console.log(i); 的console.log(ⅰ); gives this error: Uncaught SyntaxError: Identifier 'i' has already been declared 出现此错误:未捕获的SyntaxError:标识符'i'已被声明

but this one has no problem an gives the following output: 但这个没有问题,给出以下输出:

let i = 78;
console.log(i);
for (let i = 0; i < 4; i++) {
    console.log(i);
    var insideloop = 100;
}
console.log(i);

Results: 78 0 1 2 3 78 结果:78 0 1 2 3 78

The variables declared with var inside any block in the global scope are not local to that block(in your case its block of for loop) but they are inside global scope. 在全局范围内的任何块内使用var声明的变量不是该块的本地变量(在您的情况下是其for循环块),但它们位于全局范围内。

So in your first example you are trying to re declare the variable i which is already declared before in global scope with let . 因此,在您的第一个示例中,您尝试使用let重新声明已在全局范围内声明的变量i

 for(var i =0;i<5;i++){} console.log(i); //i is in global scope 

Where as let if declared in any block in your case its limited to the block of for loop. 凡为let如果你的情况下宣布任何阻止其限定的for循环块。 Its not present outside. 它不在外面。

 for(let i =0;i<5;i++){} console.log(i); //i is in global scope 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM