【问题标题】:Do i need to use var variable or let variable in this example?在这个例子中我需要使用 var 变量还是 let 变量?
【发布时间】:2020-12-20 13:07:23
【问题描述】:

当我使用 var 而不是让以下代码正常工作时,会提示用户输入文本,直到他输入单词“exit”。 但是,当我第二次输入“退出”这个词时,使用 let 不会。

let text = prompt("write something");

while(text !== "exit")
{
    let text = prompt("write something");
}

console.log("end of program);

【问题讨论】:

标签: javascript while-loop var let


【解决方案1】:

重置文本时不要使用任何东西

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多