[英]Why does my while loop with an if statement not work properly?
i am trying to code a to do list in java script, where a prompt will ask the user what they want to do and then the user has 3 options, either "new" to add a new element or "list" to check the elements already added or "quit" to quit the loop. 我正在尝试用Java脚本编写一个待办事项列表,其中提示将询问用户他们想做什么,然后用户有3个选项,“新建”以添加新元素或“列表”以检查元素已经添加或“退出”退出循环。
i tried changing the syntax by changing the position of the semicolons but it only resulted in a never ending loop which crashes my laptop! 我试图通过更改分号的位置来更改语法,但这只会导致永无休止的循环,从而使笔记本电脑崩溃!
var todo=[];
var answer=prompt("what do you want to do?");
while (answer!=="quit") {
if (answer=="list") {
console.log(todo);
}
else if (answer="new") {
var newtodo=prompt("what do you want to add?");
todo.push(newtodo);
}
}
alert("ok we're done here");
when i open the HTML file that my script is attached to, the first prompt appears as expected, when i type in "quit" it quits the loop as expected and shows the alert but when i type in "new" it keeps asking me what do u want to add? 当我打开脚本所附的HTML文件时,第一个提示按预期出现,当我键入“ quit”时,它按预期退出循环并显示警报,但是当我键入“ new”时,它一直在问我什么您要添加吗? no matter what i type and it just never ends.
不管我键入什么,它都永无止境。 Also when i type in list it keeps asking me what do u want to add even though it's supposed to list my array.
另外,当我输入列表时,它总是问我你想添加什么,即使它应该列出我的数组。 i think i have done a mistake in the syntax but i don't know what.
我认为我在语法上犯了一个错误,但我不知道该怎么办。
The issue here is that you are only prompting once , before the while loop. 这里的问题是,在while循环之前, 您只提示一次 。
Fix: at the end of the while, prompt again: 修复:在片刻结束时,再次提示:
var answer=prompt("what do you want to do?");
while (answer!=="quit") {
if (answer=="list") {
console.log(todo);
}
else if (answer=="new") { //plus here it's '==', not '='
var newtodo=prompt("what do you want to add?");
todo.push(newtodo);
}
answer=prompt("what do you want to do?");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.