【问题标题】:Why my else condition is beeing executed?为什么我的 else 条件正在执行?
【发布时间】:2017-12-17 14:47:25
【问题描述】:

我是 Javascript 新手,我正在制作一个小聊天机器人,没什么可看的,但我遇到了一个问题,如果我输入的内容与数组中的值匹配,它将执行 if 和 else条件。

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>

任何帮助将不胜感激

【问题讨论】:

  • 因为您正在检查每个索引,如果该索引不匹配,则会转到其他索引。您希望它仅在它们都不匹配时才进入,因此您需要更改逻辑。
  • 因为您在匹配之前和/或之后不断检查数组。您需要检查 all 单词并查看是否 any 匹配并且这是您的条件,而不是检查 every one 作为您的条件。有很多方法可以做到这一点。
  • 使用if (words.includes(userInput))
  • 彻底解决了!谢谢

标签: javascript arrays list arraylist


【解决方案1】:

修改你的 for 语句。

定义一个变量来检查你的脚本是否知道这个词。在for语句中,如果输入的单词在words中,则设置变量true然后break。最后,如果检查变量为假,那就说我不明白:

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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2021-12-18
    相关资源
    最近更新 更多