如何创建带有警报和提示的while循环以避免空输入? [英] How to create while loop with alert and prompt to avoid empty input?

查看:61
本文介绍了如何创建带有警报和提示的while循环以避免空输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个while循环以避免空输入.这是我的代码,我希望它循环播放,以便用户得到相同的警报,然后提示窗口,直到他/她输入名称/用户名为止.关于我做错了什么以及如何解决的任何想法?

I want to create a while loop to avoid empty input. Here's my code, I want it to loop so that the user gets the same alert and then prompt window until he/she writes a name/username. Any ideas on what I'm doing wrong and how to fix it?

<script type="text/javascript">
confirm("Wanna play?");
var name = prompt("What's your name?");
while (name.length == 0) {
    alert("Please enter your name!");
    prompt("What's your name?");
}
else {
    document.write("Welcome to my game " + name + "!" + "<br>");
}
</script>

推荐答案

@Renan建议正确.不过,如果您需要当前代码才能正常工作,则可以尝试以下操作:

@Renan suggested it right. Still, if you need the current code to work, you can try this:

<script type="text/javascript">
confirm("Wanna play?");
var name = prompt("What's your name?");
while (name.length == 0) {
    alert("Please enter your name!");
    name = prompt("What's your name?");
}
document.write("Welcome to my game " + name + "!" + "<br>");
</script>

您的代码/逻辑中有一些错误:

There are some errors in your code/logic:

  1. 为什么在 while 之后还有 else ? else 仅与 if 子句一起使用.
  2. 您要在 while 循环中要求输入名称,而不是将其分配给 name 变量.如果您未分配 name name 变量将如何更新并导致 while 循环退出?
  1. Why is there else after while? else is used with if clause only.
  2. You are asking for the name in the while loop, but not assigning it to the name variable. If you do not assign to name, how would the name variable get updated and cause the while loop to exit?

这篇关于如何创建带有警报和提示的while循环以避免空输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆