【问题标题】:`while` loop with `prompt` is never showing any `console.log`控制台未加载
【发布时间】:2019-10-29 04:33:17
【问题描述】:
var todos=["whats up dude!!"];
var input=prompt("what would you like to do?");

while(input!=="quit"){
    if(input==="list"){
        todos.forEach(function(todo, i){
            console.log(i +": "+ todo);
        });
    }
    else if(input==="new"){
        var newTodo=prompt("what do you want?");
        todos.push(newTodo);
    }
    else if(input === "delete"){
        var index = prompt("Enter index of todo to delete");
        todos.splice(index, 1);
        console.log("Todo Removed");
    }

    input=prompt("what would you like to do?");
}
console.log("You have Quit!!");

我只是想检查我的控制台是否连接到代码,并且以前它是为同一个程序连接的,但现在它甚至没有加载包含标题的基本 html 页面,并且当我之后它向控制台显示任何工作时代码。为什么会这样???

HTML 代码:

var todos=["whats up dude!!"];
var input=prompt("what would you like to do?");
    
while(input!=="quit"){
  if(input==="list"){
    todos.forEach(function(todo, i){
      console.log(i +": "+ todo);
    });
  }
  else if(input==="new"){
    var newTodo=prompt("what do you want?");
    todos.push(newTodo);
  }
  else if(input === "delete"){
    var index = prompt("Enter index of todo to delete");
    todos.splice(index, 1);
    console.log("Todo Removed");
  }
    	
  input=prompt("what would you like to do?");
}
console.log("You have Quit!!");
<!DOCTYPE html> 
<html>
  <head>
    <title>one more try</title> 
    <script type="text/javascript" src="tryy.js"></script> 
  </head> 
  <body> 
    <h1>its the last resort</h1> 
    <h4>hope i win this!!</h4> 
  </body> 
</html>

【问题讨论】:

  • 关闭代码和屏幕截图,您在提示符处,并且在提示符之前没有任何语句记录到控制台。点击确定后会发生什么?
  • 它确实有效,但在你离开循环(即输入 quit)之前你不会看到输出,因为 while 循环阻塞了其他所有内容
  • @TonyAbrams 我应该看到代码中提到的数组,之前我在它开始不再工作(或不加载)之前所做的操作
  • 你能发布以前的代码吗?

标签: javascript html google-chrome-devtools


【解决方案1】:

您可以在每个提示之前使用setTimeout 放置一个小的延迟,而不是一个永远不会控制脚本或页面的紧密循环:

var todos=["whats up dude!!"];

function interactWithToDos()
{
  var input=prompt("what would you like to do?");
  
  if(input==="list")
  {
    todos.forEach(function(todo, i)
    {
      console.log(i +": "+ todo);
    });
  }
  else if(input==="new")
  {
    var newTodo=prompt("what do you want?");
    todos.push(newTodo);
  }
  else if(input === "delete")
  {
    var index = prompt("Enter index of todo to delete");
    todos.splice(index, 1);
    console.log("Todo Removed");
  }
  
  if(input !== "quit")
  {
    setTimeout(interactWithToDos, 0);
  }
  else
  {
    console.log("You have Quit!!");
  }
}

setTimeout(interactWithToDos, 0);

【讨论】:

  • 延迟为 0 即可
  • 我不知道。更新了!
猜你喜欢
  • 2018-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-02
  • 1970-01-01
  • 2021-07-24
  • 2014-12-07
相关资源
最近更新 更多