[英]Javascript promo code prompt - endless while loop
We're using a promo code to allow people access to a page. 我们正在使用促销代码来允许人们访问页面。 It doesn't have to be secure - just trying to give the customers a code prompt to make them feel special.
它不一定是安全的-只是试图给客户一个代码提示,使他们感到特别。
So I used this code... obviously I am doing something wrong because the browser keeps checking for the code even after they entered it (and eventually the page crashes). 因此,我使用了这段代码...显然我在做错什么,因为浏览器即使在输入代码后仍会继续检查代码(最终页面崩溃)。 I tried break;
我试图休息; at the end, but then prompt doesn't happen.
最后,但没有提示。
I would appreciate any help with this. 我将不胜感激。
All I want to do is get rid of the endless loop here. 我想要做的就是摆脱这里无尽的循环。
var secret; while (secret !== "1") if (secret !== "2") if (secret !== "3") if (secret !== "4") { secret = prompt("What is the secret password?"); };
The problem is improper use of while
mixed with if
. 问题是使用不当造成的
while
夹杂if
。 Maybe you should consider an other approach: 也许您应该考虑其他方法:
var askSecret = function askSecret() { var secret = prompt("What is the secret password?"); if(secret !== "theSecret") { askSecret(); } }; askSecret();
Edit: multiple passwords/secrets 编辑:多个密码/秘密
In the previous example, the only valid secret/password is "theSecret". 在前面的示例中,唯一有效的机密/密码是“ theSecret”。 If you need to have more than one secret/password, you'll have to extend the conditional with an AND
&&
operator: 如果需要多个秘密/密码,则必须使用AND
&&
运算符扩展条件:
var askSecret = function askSecret() { var secret = prompt("What is the secret password?"); if( secret !== "theSecret" && secret !== "TheOtherSecret" && secret !== "TheThirdValidSecret" ) { askSecret(); } }; askSecret();
Your code goes into an infinite loop if the user types any of the numbers in the if (secret != XX)
lines. 如果用户在
if (secret != XX)
行中键入任何数字, if (secret != XX)
代码将陷入无限循环。 This is because the while
condition is met, but the if
condition fails, so it skips over the prompt()
function and repeats the while
. 这是因为满足
while
条件,但是if
条件失败,因此它跳过了prompt()
函数并重复while
。 Since this doesn't change answer
, it keeps doing this over and over. 由于这不会改变
answer
,因此会不断重复执行此操作。
If you want to check for multiple possible answers, do them all in the while
statement: 如果要检查多个可能的答案,请在
while
语句中全部进行:
var secret; while (secret != "1" && secret != "2" && secret != "3" && secret != "4") { secret = prompt("What is the secret password"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.