我有一个问题。我使用聊天机器人,我想添加更多单词,但它不起作用。如何将数组与单词一起使用?
感谢您的帮助。
function bot(message) {
var words = ['hello', 'hi', 'hey'];
if(wordChecker(message, words)) {
var messageArray = [
'Hello to you too!',
'I said hello first :)',
'Greeting, human.'
];
sendMessage(messageArray);
}
else if (wordChecker(message, words)) {
var words = ['1', '2', '3'];
var messageArray = [
'Word1',
'Word2',
'Word3'
];
sendMessage(messageArray);
}
else if (message.indexOf('good fine') >= 0) {
var messageArray = [
'Okay, so what do you want to talk about?',
'Okay, what is your problem? Tell me.',
'Do you have something to say? Say it. Let it out your chest.'
];
sendMessage(messageArray);
}
WordChecker功能:
function wordChecker(message, words){
var has = false;
for (var i = 0; i < words.length; i++) {
if(message.indexOf(words[i])) {
has = true;
}
}
return has;
}
最佳答案
你想扩展你的代码,我在一开始就添加了一个database
数组来将你的代码和数据部分分开。
function bot(message) {
var database = {
'hello|hi|hey' : ['Hello to you too!','I said hello first :)','Greeting, human.'], //Separate with | if you want output when any one of all is match
'mango|banan' : ['I am mango man!','I Love Mango :)','Mangoes are my favrout.'], // Another words' set
'price' : ['What is price of your services!','What best price you can give me :)','My price is unbearable.','Can you give me down time'] // Single Varialbe
};
var output = [];
for (var words in database) {
if (database.hasOwnProperty(words)) {
$constraint_or = words.split("|");
for (i=0; i<$constraint_or.length; ++i)
if(message.indexOf($constraint_or[i]) >= 0){
output = output.concat(database[words]);
break;
}
}
}
console.log(output); // For testing output
if(output.length>0)
sendMessage(output);
}
bot("hi hello"); // Calling for test
关于JavaScript/jQuery 使用更多单词而不是 IndexOf - 聊天机器人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33972709/