简体   繁体   English

简单的Javascript提示验证循环不起作用

[英]Simple Javascript prompt validation loop not working

I cant seems to get this to work. 我似乎无法使它正常工作。

<script language="JavaScript">
var name = null;
do
{
    var name = prompt("Please enter your full name","");
}
while(name != null);
</script>

When you enter a blank string and press OK, it returns a empty string not null, null is returned only when you press cancel. 输入空白字符串并按OK时,它将返回一个不为null的空字符串,仅当您按cancel时才返回null

You can test for truthyness of the returned value 您可以测试返回值的真实性

var name = null;
do {
  name = prompt("Please enter your full name");
  console.log(name)
}
while (!name);
console.log('done', name)

I would use a boolean value: 我将使用布尔值:

var name = false;
do
{
    name = prompt("Please enter your full name",'');
}
while(!name); // While name is not true

Also you were re-declaring the name var again on within the do loop, remove the var in the loop. 另外,您在do循环中再次声明了var的name ,请在循环中删除var

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM