Stuck in else if loop in Javascript

ByteTheBits

I'm doing an exercise for a class and we are creating a Todo list.

My issue is that when I type in my Todo and press enter, I get the message Enter new Todo, instead of Added todo.

It seems I'm stuck in this else if loop and it won't go to the next else if statement.

var todos = ["Buy New Turtle"];

window.setTimeout(function() {

  var input = prompt("What would you like to do?");

  while(input !== "quit") {

    if(input === "list") {
      console.log("**********");
      todos.forEach(function(todo, i) {
        console.log(i + ": " + todo);
      })
      console.log("**********")
    }
    else if(input === "new") {
      var newTodo = prompt("Enter new todo");
      todos.push(newTodo);
      console.log("Added todo");
      }

    else if(input === "delete"){
      var index = prompt("Enter index of todo to delete");
      todos.splice(index, 1);
      }
  }
    input = prompt("What would you like to do?");

  console.log("OK, YOU QUIT THE APP");
}, 500);

Jack Bashford

You need to place the redeclaration of input inside the while loop. Also check if input is truthy - that way if someone closes the prompt box it doesn't crash.

var todos = ["Buy New Turtle"];

window.setTimeout(function() {

  var input = prompt("What would you like to do?");

  while (input !== "quit" && input) {

    if (input === "list") {
      console.log("**********");
      todos.forEach(function(todo, i) {
        console.log(i + ": " + todo);
      })
      console.log("**********")
    } else if (input === "new") {
      var newTodo = prompt("Enter new todo");
      todos.push(newTodo);
      console.log("Added todo");
    } else if (input === "delete") {
      var index = prompt("Enter index of todo to delete");
      todos.splice(index, 1);
    }

    input = prompt("What would you like to do?");
  }

  console.log("OK, YOU QUIT THE APP");
}, 500);

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事