英文:
while loop won't stop even condition evaluates to false
问题
let checkOrFold = undefined;
while (checkOrFold !== 'check' && checkOrFold !== 'fold') {
checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold !== 'check' && checkOrFold !== 'fold');
}
console.log('finish') here;
问题可能是变量 checkOrFold
在 while
循环内被重新声明了一次,导致循环无法正常退出。在上述代码中,我修复了这个问题。
英文:
let checkOrFold = undefined
while(checkOrFold != 'check' && checkOrFold != 'fold'){
let checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold != 'check' && checkOrFold != 'fold')
}
console.log('finish') here
even the console is logging false but prompt keeps popping up. What could be wrong?
Tried debugging. When 'check' or 'fold' is typed, console.log should show finish.
答案1
得分: 1
You’re declaring another variable with the same name in the while loop. Remove the let
from within the while loop and you should get what you’re looking for.
你在while循环中又声明了一个同名变量。在while循环内去掉`let`,你应该会得到你想要的结果。
let checkOrFold = undefined;
while(checkOrFold != 'check' && checkOrFold != 'fold'){
checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold != 'check' && checkOrFold != 'fold');
}
console.log('finish');
英文:
You’re declaring another variable with the same name in the while loop. Remove the let
from within the while loop and you should get what you’re looking for.
let checkOrFold = undefined;
while(checkOrFold != 'check' && checkOrFold != 'fold'){
checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold != 'check' && checkOrFold != 'fold');
}
console.log('finish');
答案2
得分: 1
你可能希望在 while 循环之外只提示一次,以便 checkOrFold
有机会接收输入。此外,您在循环内意外地设置了一个分开的块级作用域变量 checkOrFold
,您需要在整个代码部分使用相同的 checkOrFold
才能正常工作。
解决方案:
let checkOrFold = undefined;
checkOrFold = prompt(`check or fold?`);
while(checkOrFold != 'check' && checkOrFold != 'fold'){
checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold != 'check' && checkOrFold != 'fold')
}
console.log('finish')
如果您需要更多帮助,请随时告诉我。
英文:
You probably want to prompt outside the while loop once, so checkOrFold
has a chance to receive an input. You also, by accident, setup a separate block scoped variable checkOrFold
inside the loop, you need to use the same checkOrFold
for the whole portion of code to work.
Solution:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let checkOrFold = undefined;
checkOrFold = prompt(`check or fold?`);
while(checkOrFold != 'check' && checkOrFold != 'fold'){
checkOrFold = prompt(`check or fold?`);
console.log(checkOrFold != 'check' && checkOrFold != 'fold')
}
console.log('finish')
<!-- end snippet -->
答案3
得分: 0
尝试匹配响应,直到你获得“check”或“fold”作为响应。
当(checkOrFold = 'check' || checkOrFold = 'fold')
英文:
try matching the response till you get either check or fold as a response
while(checkOrFold = 'check' || checkOrFold = 'fold')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论