我们正在尝试创建一个简单的#34;聊天机器人"根据搜索查询中的关键字与您进行互动。
示例:您键入"最近的栏在哪里?"并且机器人会给你答案"它在这里bla bla bla"。
我们正试图通过数组存储可能的关键字和答案来实现这一目标。我们设法运行一个阵列,但无法通过它们全部运行以查看是否有任何适合其他选项的关键字。我们怎么做?
使用$ each是正确的方法吗?
var search = [
{
"words":["hey", "bro"],
"result":"Hey man!"
},
{
"words":["ninja","stuff"],
"result":"Other answer"
}
];
var query = search.words;
var answer = search.result;
$("#txt").keypress(function(e) {
if(e.which == 13) {
var str = $('#txt').val();
var res = str.toLowerCase();
if (query.some(function(v) { return res.indexOf(v) >= 0; })) {
$('#result').html(answer);
}
else {
$('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? ');
}
}
});
})(jQuery);
答案 0 :(得分:-1)
var search = [{
"words": ["hey", "bro"],
"result": "Hey man!"
}, {
"words": ["ninja", "stuff"],
"result": "Other answer"
}];
$("#txt").keypress(function(e) {
//Detect key *ENTER* pressed
if (e.which == 13) {
//Get the string entered and switch to lowercase
var str = $('#txt').val().toLowerCase();
//Init found to false
var found = false;
//Iterate each object of the arrat *search*
$.each(search, function(index, value){
//Check if the entered string is present in the array of words
if(value.words.indexOf(str) !== -1){
//We found the entered word
found = true;
//Display the result linked to the word entered
$('#result').html(value.result);
//Exit from the each() method
return false;
}
});
//Check if we found our word
if(!found)
//Display the error message if you dont find the entered word
$('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? ');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">
<p id="result"></p>