我一直在编写一个简单的聊天机器人。当我试图从switch语句切换到map数组时,我遇到了这个错误:TypeError:map [msg [1]]不是函数
我想知道是什么导致了这个错误,以及如何修复它。
代码示例:
function simpleReactSearch(handle, msg, pureMsg, priv) {
if (priv > 0) {
var map = {
"hooray": heyListen(handle, msg, pureMsg, priv),
"hellowound": helloWound(handle, msg, pureMsg, priv)
}
map[msg[0]]();
}
}
function heyListen(handle, msg, pureMsg, priv) {
var map = {
"hi": commonReact("greeting", handle, priv),
"hello": commonReact("greeting", handle, priv)
}
map[msg[1]](); //The line of the error.
}
function helloWound(handle, msg, pureMsg, priv){return;}
function commonReact(react, handle, priv) {
switch(react) {
case "greeting":
return("Hi there, "+handle+"!");
case "morning":
return("Blah blah blah, "+handle+"!");
}
}
var msg = new Array(),
pureMsg = new Array();
msg[0] = "hooray";
msg[1] = "hi";
pureMsg[0] = "hooray";
pureMsg[1] = "hi";
var reaction = simpleReactSearch("Wound",msg,pureMsg,2);
if (reaction !== null) {
alert(reaction);
}
然而这样的事情很好用:
function func1(){alert("func1");}
function func2(){alert("func2");}
function func3(){alert("func3");}
var msg = new Array();
msg[0] = "hooray";
msg[1] = "hi";
var map = {
"hi": func1,
"hello": func1,
"test": func2,
"whatever": func3
}
if(msg[0] === "hooray") {
map[msg[1]]();
} else {
alert("failure");
}
答案 0 :(得分:2)
var map = { "hooray": heyListen(handle, msg, pureMsg, priv), "hellowound": helloWound(handle, msg, pureMsg, priv) }
您已经在调用这些函数,并将结果(undefined
值)分配给map
个广告位。当您尝试执行这些操作时,您会收到错误消息,表明它们不起作用。
相反,请自行分配函数对象,并仅在调用它们时传递参数:
var map = {
"hooray": heyListen,
"hellowound": helloWound
}
map[msg[0]](handle, msg, pureMsg, priv);
同样适用于heyListen
代码。