繁体   English   中英

让关键字在块 scope 之后不显示全局值

[英]Let keyword not showing the global value after the block scope

我正在学习 ES6,在https://www.w3schools.com/js/js_let.asp我看到了一个例子:

let i = 5;
for (let i = 0; i < 10; i++) {
  // some statements
}
// Here i is 5

所以,我以自己的方式尝试:

 const name='ashwin'; let message='suju'; for(const i = 0; i < 10; i++) { message = `${i} count now`; console.log(message); } console.log(message+'aa');
 <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html>

此时我预期的 output console.log(message+'aa'); 是: sujuaa但我看到'9 count nowaa' 。因为在块 scope 之后,在 let 关键字中,它访问为全局 scope 定义的值。它也已在 w3schools 中显示。 有人可以向我澄清一下,为什么在完成块 scope 之后,我没有得到全局 scope 的值?

您在全局 scope 中收到消息 - 问题是,您还在循环中修改该消息。 要创建一个修改块作用域变量的循环,请在循环中用let重新定义它:

 let name = 'ashwin'; let message = 'suju'; for (let i = 0; i < 10; i++) { let message = `${i} count now`; console.log(message); } console.log(message + 'aa');

在您的示例中,您正在循环内修改message ,而不是复制它,因此您将修改全局变量。 仅使用let不会将其限制在块内并自动制作副本 - 在您的情况下,它只是防止它在全局 scope 中使用它时被声明两次。

 let name='ashwin'; let message='suju'; for(let i = 0; i < 10; i++){ let message=`${i} count now`; // In your example from w3schools he used let 2x first in defining in the global scope and let for defining the variable. In your example you only used let one time in the global scope, defining it again in the local scope will give you your desired output. console.log(message); } console.log(message + 'aa');
 <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> </html>

暂无
暂无

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

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