简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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