2016-03-09 33 views
1

我正在製作一個簡單的AI聊天程序。我有一個我可以問的問題列表,並根據我所提出的問題給出了答案。從數組中選擇鍵值對時不能執行功能

----------------------這是我的鍵值對數組----------------- ----------

var dictionary = { 
    "HOW ARE YOU?": ["im fine thanks", 
         "Im okayish", 
         "im good, how are you?" 

        ], 
    "SUP?" : ["nothing much", "google" window.open("http://www.google.com");] 
} 

如何使用隨機函數從數組中選擇隨機輸出。

var random = parseInt(Math.random() * dictionary[question.toUpperCase()].length); // Returns a random number between 0 and the arraysize 

answer = dictionary[question.toUpperCase()][random]; 

現在我的問題是,假設我問AI「sup?」它應該顯示「沒有多少」,或者說「谷歌」,並打開谷歌。

但這不起作用。基本上該數組中的window.open()會導致javascript崩潰。

如果我的數組更改爲: -

"SUP?" : ["nothing much", "google" ] 

即沒有window.ppen()功能,它的工作。

有什麼建議嗎?

回答

1

你可以嘗試多一點複雜的數據結構:

var dictionary = { 
    "HOW ARE YOU?": [{ message: "im fine thanks" }, 
        { message: "Im okayish" }, 
        { message: "im good, how are you?" }], 
    "SUP?" : [{ message: "nothing much" }, 
       { message: "google", 
       action: function() { window.open("http://www.google.com"); } 
       }] 
} 

然後你檢查是否有選擇的答案有一個動作,調用它。

function randomElem(array) { 
    return array[parseInt(Math.random() * array.length)]; 
} 

function getAnswer(question) { 
    var answers = dictionary[question.toUpperCase()]; 
    if (!answers) { 
     return { message: "I dont know what you mean!" }; 
    } else { 
     return randomElem(answers); 
    } 
} 

function processInput(question) { 
    var answer = getAnswer(question); 
    show(answer.message); // replace it with whatever you use to show the answer 
    if (answer.action) { 
     answer.action(); 
    } 
} 
+0

函數processInput(question){ \t var random = parseInt(Math.random()* dictionary [question.toUpperCase()] .length); \t var answer = dictionary [question.toUpperCase()] [random]; \t \t show(answer.message); \t \t if(answer.action){ \t answer.action(); } else { \t answer =「我不知道你的意思!「; \t} -------------- oops,我不知道爲什麼我不能格式化這個,無論如何,這就是我現在所做的和答案沒有任何存儲之後,我認爲我們不檢查問題是否在字典中可用 – Jasim

+0

@Jasim我添加了一個檢查,如果在字典中有任何問題的答案,我還將代碼分成更小的函數 –

+0

工作完美!現在我正打算擴展它的功能就像一個基本的AI,例如: - 如果用戶詢問「你是怎麼做的」而不是「你怎麼樣」,因爲「你怎麼樣」與「你好嗎」用戶問到「你好嗎」,因此,使用JS是一種好的方法?我目前是一名學習CS和BIS的本科生,只是把它當做愛好.JS會是一個很好的選擇來製作一個AI程序嗎? I在編譯器顯示的時候肯定會用java e錯誤,但是這個JS中的var數據結構讓東西變得很簡單,我覺得我應該堅持下去, – Jasim

0

"google" window.open("http://www.google.com");是不正確的JSON值。 相反,你可以做類似的, if(answer === 'google') window.open("http://www.google.com"); 並讓dictionary只存儲字符串。

+0

多數民衆贊成在最初我是如何做的東西,但後來這意味着很多循環,因此我決定將其分割成數組。 如果AI只能打開谷歌,你的解決方案是好的。 – Jasim

+0

但如果我喜歡50個命令來打開不同的網站,那會讓它變慢呢? – Jasim

0

嘗試打開谷歌鏈接你所得到的答案後

var random = parseInt(Math.random() * dictionary[question.toUpperCase()].length); 
answer = dictionary[question.toUpperCase()][random]; 
if(answer=="google"){ 
window.open("http://www.google.com") 
} 
+0

這是行不通的, 但如果我創建了50個不同的命令來打開不同的網站,這種方式效率不高,但它確實解決了問題。 看看lukasz給出了一個答案,那就是我正在尋找的。 – Jasim