gpt4 book ai didi

javascript - 类型错误 : map[msg[1]] is not a function

转载 作者:行者123 更新时间:2023-11-30 17:43:10 25 4
gpt4 key购买 nike

我一直在编写一个简单的聊天机器人。当我尝试从 switch 语句切换到 map 数组时,遇到了这个错误:TypeError: map[msg[1]] is not a function

我想知道是什么导致了这个错误,以及如何修复它。

代码示例:

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");
}

最佳答案

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 代码也是如此。

关于javascript - 类型错误 : map[msg[1]] is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com