2017-03-09 36 views
0

这段代码有些问题,但我无法弄清楚它是什么。该页面无法正常工作或执行其应有的操作。我需要一个提示输入密码的代码,并将尝试限制为3.第三次尝试后,它需要一个警告框。我没有添加警告框之后的内容。Javascript Prompt Box Loops

<script> 
var attempts = 3; 
var answer = prompt("Password: "); 
while (attempts != 0) 
{ 
    if (answer == "Psycho") 
    { 
     document.write("These are pictures of my kitten and  her things."); 
    } 
    else 
    { 
     answer = prompt("Password: "); 
     attempts--; 
    } 
} 
if (attempts = 0) 
{ 
    alert("Incorrect Password"); 
} 
</script> 
+1

'='是赋值 – epascarello

回答

0

有几个选项可以修复您的代码。 完成工作后,您可以返回。

<script> 
var attempts = 3; 
var answer = prompt("Password: "); 
while (attempts != 0) 
{ 
    if (answer == "Psycho") 
    { 
     document.write("These are pictures of my kitten and  her things."); 
     return; 
    } 
    else 
    { 
     answer = prompt("Password: "); 
     attempts--; 
    } 
} 
if (attempts == 0) 
{ 
    alert("Incorrect Password"); 
} 
</script> 

或者,如果你已经失败了

<script> 
var attempts = 4; 
var answer = prompt("Password: "); 
while (attempts > 0 && answer != "Psycho") 
{ 
    answer = prompt("Password: "); 
    attempts--; 
} 

if (attempts == 0) 
{ 
    alert("Incorrect Password"); 
} 
else 
{ 
    document.write("These are pictures of my kitten and  her things."); 
} 
</script> 
+0

和你的代码有相同的问题,问题的OP – epascarello

+0

@epascarello卫生署!固定 –

0

你有几个问题我想提前返回。用户输入提示后应检查输入。或者最后一个条目不会被检查。下一个问题是你没有退出循环。另一个问题是,=是如此分配,因此如果你分配零,而不是检查它是否为零。

var attempts = 3; 
 
while (attempts > 0) { 
 
    var answer = prompt("Password: "); 
 
    if (answer == "Psycho") { 
 
    document.write("These are pictures of my kitten and her things."); 
 
    break; 
 
    } 
 
    attempts--; 
 
} 
 
if (attempts == 0) { 
 
    alert("Incorrect Password"); 
 
}