0

我正在构建一个聊天机器人,一些脚本如下

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() ,用户可以在其中输入是或否和聊天机器人然后将根据用户的回复给出回复。但是现在如果我输入“问我一个问题”,聊天机器人会问“你吸烟吗?”,但是当我输入“不”时,聊天机器人不会说“很高兴听到你不吸烟!”说“为什么不呢?” 基于新的数组。

更新(根据建议更改,但仍然无效):

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
}
4

1 回答 1

2

JavaScript 中的相等比较使用==or===运算符;=总是赋值。所以在这里:

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.*"),因为您不必担心使用正则表达式文字进行两层转义。

于 2016-02-24T05:15:02.283 回答