2013-12-17 18 views
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"); 
} 

回答

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代碼。

+0

函數也可以返回函數。當我需要一種編程方式來構建回調時,我使用了這種技術。我在使用部分應用程序和綁定時也使用該技術。下劃線的綁定和部分對此非常完美。 – Sukima

+0

或者將值設置爲函數:'hooray:function(){return heyListen(handle,msg,pureMsg,priv); }' –

+0

@Sukima:當然,但是*在這裏*他們沒有返回函數;-)我猜想OP不想在這裏使用閉包。 – Bergi

相關問題