我正在构建一个聊天机器人,一些脚本如下所示
var convpatterns = new Array (
new Array (".*hi.*", "Hello there! ","Greetings!"),
new Array (".*ask me*.", Smoking),
new Array (".*no*.", "Why not?"),正如你所看到的,如果用户输入"hi",聊天机器人会回复Hello there或Greetings!如果用户输入“向我提问”,它就会链接到Smoking()函数。
function Smoking(){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Do you smoke?");
return field
SmokingAnswer()
}
function SmokingAnswer(){
var userinput=document.getElementById("messages").value;
if (userinput="yes"){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Oh no! Smoking is not good for your health!");
}else if(userinput="no"){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Good to hear that you are not smoking!");
}
return field
}因此,在Smoking()函数中,聊天机器人将口头询问用户“你吸烟吗?”,然后它应该链接到下一个函数,即SmokingAnswer(),用户可以在该函数中输入yes或no,然后聊天机器人将根据用户的响应给出答复。然而,现在如果我输入“问我一个问题”,聊天机器人会问“你吸烟吗?”,但当我输入“不”时,聊天机器人不会说“很高兴听到你没有吸烟!”,而是说“有何不可?”基于新的数组。
更新(根据建议进行了更改,但仍然不起作用):
function initialCap(field) {
field = field.substr(0, 1).toUpperCase() + field.substr(1);
return field
}
function Smoking(){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Do you smoke?");
SmokingAnswer()
}
function SmokingAnswer(){
var userinput=document.getElementById("messages").value;
if (userinput=="yes"){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Oh no! Smoking is not good for your health!");
}else if(userinput=="no"){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Good to hear that you are not smoking!");
}
return field
}发布于 2016-02-24 13:15:02
JavaScript中的相等比较使用==或===运算符;=始终为赋值。所以这里:
if (userinput="yes"){...您将"yes"赋值给userinput,然后进入if的主体(因为它最终是if ("yes"),而"yes"是真的,所以我们遵循分支)。它应该是:
if (userinput == "yes"){或
if (userinput === "yes"){==和===之间的区别在于,== (“松散的”相等运算符)会在必要时(有时以令人惊讶的方式)进行类型强制,以试图使操作数相等,但===不会(不同类型的操作数总是不相等)。
单独:
function Smoking(){
window.iSpeech.speak(speakPluginResultHandler,nativePluginErrorHandler,"Do you smoke?");
return field
SmokingAnswer()
}这里永远不会调用SmokingAnswer函数,因为它是在return field之后调用的。因此,要么是Smoking函数在SmokingAnswer被调用之前返回,要么是因为field未定义而抛出错误(它没有显示在代码中的任何地方);无论哪种方式,SmokingAnswer都不会被调用。
附注:使用数组初始值设定项可以更简洁地编写初始数组:
var convpatterns = [
[".*hi.*", "Hello there! ","Greetings!"],
[".*ask me*.", Smoking],
[".*no*.", "Why not?"],
// ...
];您还可以查看正则表达式文字,而不是字符串(/.*hi.*/而不是".*hi.*"),因为您不必担心使用正则表达式文字进行两层转义。
https://stackoverflow.com/questions/35593736
复制相似问题