首页 > 解决方案 > 我正在尝试在 javascript 中编写一个 while 循环。我的 console.log 不打印请求的消息

问题描述

var ask = prompt('Are we there yet???');

while (ask != 'y') {

  if (ask[0] === 'y') {
    // For some unknown reason to me my solution will not print the message.
    console.log('Yea, we made it!!!');
  } else {
    var ask = prompt('Are we there yet???');
  };

}

标签: javascriptwhile-loop

解决方案


您的代码将 while 循环内的变量设置为提示的输出,这就是循环无法访问它的原因。

为了实现你的目标,你需要这样的东西:

while (prompt('Are we there yet???') !== 'y') {}
console.log('Yea, we made it!!!');

基本上,代码进入一个无限循环,要求用户y在继续代码之前输入,在这种情况下,将消息记录到控制台。


推荐阅读