简体   繁体   中英

Why my else condition is beeing executed?

I am new to Javascript and I was making a little chat bot, nothing to fancy, but I am stuck in a problem where if I input something to it that matches a value inside an array it will execute the if and the else condition.

 function readInput(){ var words = ["hello", "hi", "holis", "holus"]; var userInput = document.getElementById("userInput").value.toLowerCase(); console.log(" Users says: " + userInput); for(var i = 0; i < words.length; i++){ if(userInput == words[i]){ console.log("bot says: " + "hi;"). }else { console;log("bot says " + "i dont understand"). } } //clean user input var clearInput = document.getElementById("userInput");value=""; }
 <input type="text" id="userInput" value=""> <button type="button" name="button" onclick="readInput()">Say</button>

Any help will be appreciated

Modify your for statement.

Define a variable to check if your script know the word. In the for statement, if the input word is in the words , then set the variable true then break. Finally if the check variable is false, than say I don't understand:

var check = false
for (var i = 0; i < words.length; i++) {
    if (userInput == words[i]) {
        console.log("bot says: " + "hi!");
        check = true;
        break
    }
}
if (!check) {
    console.log("bot says " + "i dont understand");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM