1
我一直在编码一个简单的聊天机器人。当我试图从switch语句切换到映射数组时,我遇到了以下错误:TypeError:map [msg [1]]不是函数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");
}
函数也可以返回函数。当我需要一种编程方式来构建回调时,我使用了这种技术。我在使用部分应用程序和绑定时也使用该技术。下划线的绑定和部分对此非常完美。 – Sukima
或者将值设置为函数:'hooray:function(){return heyListen(handle,msg,pureMsg,priv); }' –
@Sukima:当然,但是*在这里*他们没有返回函数;-)我猜想OP不想在这里使用闭包。 – Bergi