此 JavaScript 代码应该无限期地运行,直到提供空字符串为止,但事实并非如此。为什么?

let yourName;

do {

  yourName = prompt("Who are you?");

} while (!yourName);

console.log(yourName);

此代码在在线教科书中给出:https ://eloquentjavascript.net/02_program_struct.html


我还尝试以这种方式在控制台中运行它:


let funGame;

do { 

    funGame = prompt("enter anything to get rid of this Game");

} while (!funGame); 

console.log(funGame);

我正在使用谷歌浏览器来测试这段代码。此代码仅运行一次,而它应该无限期地运行,直到提供空字符串为止。


炎炎设计
浏览 96回答 3
3回答

ABOUTYOU

“Do While”一直有效,直到条件为真。在您的情况下,代码要求您必须编写一个名称才能从“do while”退出。let yourName;do {  yourName = prompt("Who are you?");} while (!yourName);console.log(yourName);如果您不希望出现这种情况,而希望出现另一种情况,您可以删除“!” 在“做一会儿”let yourName;    do {      yourName = prompt("Who are you?");    } while (yourName);    console.log(yourName);在这种情况下,您会遇到相反的情况。

收到一只叮咚

您可以检查字符串的长度并运行循环,直到yourName找到空白内容。do {  var yourName = prompt("Who are you?");  console.log(yourName);  if (!yourName){    break;  }} while (yourName.trim().length > 0);

Qyouu

这是一个简单的解决方案,yourName != null检查提示是否被取消let yourName;do {  yourName = prompt("Who are you?");} while (yourName != "" && yourName != null);console.log(yourName);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript