Javascript 为什么在这里找不到变量?
它告诉我变量机密无法找到Javascript 为什么在这里找不到变量?,javascript,Javascript,它告诉我变量机密无法找到 // Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame" do { let secret = prompt("What is the secret password?"); } while ( secret !== "sesame"); // This should run aft
// Display the prompt dialogue while the value assigned to `secret` is not equal to "sesame"
do {
let secret = prompt("What is the secret password?");
} while ( secret !== "sesame");
// This should run after the loop is done executing
alert("You know the secret password. Welcome!");
让我们有块范围。使用
const
或var
var secret; // or const secret;
do {
secret = prompt("What is the secret password?");
} while ( secret !== "sesame");
编辑:
关于@James的建议
let secret;
do {
secret = prompt("What is the secret password?");
} while ( secret !== "sesame");
也将起作用,因为现在通过在
do之外定义它,let
的范围增加了,而语句的块就像其他人已经评论过的那样:let
有一个严格的范围规则。
改用var
或const
。或者使用let
在块外,更高一级。let
有一个严格的范围规则:do{var secret=prompt(“什么是秘密密码?”);}while(secret!=“sesame”)代码>这是否回答了您的问题?由于已将声明移到块外,因此也可以在此处使用let
,但const
将不起作用,因为您正在使用提示响应重新定义变量。请勿使用const。