提示只循环一次

时间:2017-03-07 13:50:41

标签: javascript while-loop prompt

我正在学习javascript。我试图创建一个循环,不断提示用户进行活动,然后将其存储在数组中。如果用户输入' DONE'它停止要求输入。

问题是,在运行一次之后,即使没有满足while条件,循环也会结束。

我使用jsbin作为练习js的沙箱。这是代码:

var todoList = [];
while (input != "DONE") {
var input = prompt("Please enter an activity. When you are done type 'DONE'.");
todoList.push(input);
}

由于

4 个答案:

答案 0 :(得分:1)

您的输入变量仅在您的循环内。在使用var input = "";

的循环之前初始化它

然后从循环中删除var(因为您要为现有变量赋值),它应该可以正常工作。

var todoList = [];
var input = "";
while (input != "DONE") {
  input = prompt("Please enter an activity. When you are done type 'DONE'.");
  todoList.push(input);
}

答案 1 :(得分:1)

Var需要在循环之外。

var input;
var todoList = [];
while (input != "DONE") {
     input = prompt("Please enter an activity. When you are done type 'DONE'.");
     todoList.push(input);
}

答案 2 :(得分:0)

@Afixoftrix你的代码在浏览器控制台和js小提琴中运行良好.JsBin对无限循环有一些保护。在console中查看它。如果你需要学习javascript,不要在第三方工具中学习它,使用代码编辑器或浏览器控制台这有助于获得有关javascript的更多知识。enter image description here

查看更多:JS Bin while infinite loop

Js fiddle consolelog:enter image description here

答案 3 :(得分:0)

我们应该能够处理大写和小写字母。

{{1}}

jsfiddle