当我使用var而不是let时,下面的代码运行良好,并提示用户输入文本,直到他输入单词"exit“。然而,当我第二次输入单词"exit“时,使用字母却不起作用。
let text = prompt("write something");
while(text !== "exit")
{
let text = prompt("write something");
}
console.log("end of program);
发布于 2020-09-01 12:06:16
在重置文本时不要使用任何内容
let text = prompt("write something");
while(text !== "exit")
{
text = prompt("write something"); // nothing, uses text in outer scope
}
console.log("end of program);
当您在while循环中使用'let‘时,您正在创建一个单独的变量,其作用域为该语句块。当您使用var时,它是函数的hoisted,或者如果不在函数中,则是全局对象(或者如果您不使用var、let或const,而只是尝试使用一个变量而不声明它)。由于变量使用var在相同的函数(或全局作用域)中,因此它们引用相同的内容。
当使用let时,变量的作用域是代码块。因此,while语句块内的'text‘变量并不引用在该块外部声明并在while条件中使用的同一个'text’变量。以下是链接中的示例:
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
https://stackoverflow.com/questions/63687301
复制