【发布时间】: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