Javascript函数没有链接到下一个

Javascript function not linking to the next one

本文关键字:下一个 链接 函数 Javascript      更新时间:2023-09-26

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

var convpatterns = new Array (
new Array (".*hi.*", "Hello there! ","Greetings!"),
new Array (".*ask me*.", Smoking),
new Array (".*no*.", "Why not?"),

如您所见,如果用户输入"嗨",聊天机器人会回复您好或问候!如果用户输入"问我一个问题",它将链接到 Smoke() 函数。

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
}

因此,在Smoke()函数中,聊天机器人将口头询问用户"你吸烟吗?",然后它应该链接到下一个功能,即SmokeAnswer(),用户可以在其中输入是或否,然后聊天机器人将根据用户的响应给出回复。然而,现在如果我输入"问我一个问题",聊天机器人会问"你抽烟吗?",但是当我输入"不"时,聊天机器人不会说"很高兴听到你不吸烟!",而是说"为什么不?"基于新的数组。

更新(根据建议更改,但仍然不起作用):

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
}

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