2016-11-08 55 views
-1

我們正在嘗試創建一個簡單的「聊天機器人」來與之進行交互,從而根據搜索查詢中的關鍵字給出答案。

例如:您輸入「最近的酒吧在哪裏?」而機器人會給你答案「它在這裏嗒嗒嗒嗒」。

我們試圖通過存儲可能的關鍵字和答案通過數組來做到這一點。我們設法通過一個數組運行,但無法全部運行,以查看是否有任何適合其他選項的關鍵字。我們如何做到這一點?

正在使用$每個正確的方式去?

var search = [ 
    { 
    "words":["hey", "bro"], 
    "result":"Hey man!" 
    }, 
    { 
    "words":["ninja","stuff"], 
    "result":"Other answer" 
    } 
]; 

var query = search.words; 
var answer = search.result; 

$("#txt").keypress(function(e) { 
    if(e.which == 13) { 

    var str = $('#txt').val(); 

    var res = str.toLowerCase(); 

    if (query.some(function(v) { return res.indexOf(v) >= 0; })) { 
     $('#result').html(answer); 
     } 
    else { 
     $('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? '); 
    } 
} 

    }); 

})(jQuery); 
+0

'search'是一個數組,因此'search.words'和'search.result'將無法正常工作 – Weedoze

+0

@Weedoze我們清楚地意識到這一點。我們曾經使用'search [0] .words'和結果相同。但是這限制了我們只展示那條特定的線條,而不是一般的我們正在尋找的線條。 –

+0

'var query = search.words;'wat。當然你想要某種循環。 –

回答

-1

var search = [{ 
 
    "words": ["hey", "bro"], 
 
    "result": "Hey man!" 
 
}, { 
 
    "words": ["ninja", "stuff"], 
 
    "result": "Other answer" 
 
}]; 
 

 

 
$("#txt").keypress(function(e) { 
 
    //Detect key *ENTER* pressed 
 
    if (e.which == 13) { 
 
    
 
    //Get the string entered and switch to lowercase 
 
    var str = $('#txt').val().toLowerCase(); 
 
    //Init found to false 
 
    var found = false; 
 
    
 
    //Iterate each object of the arrat *search* 
 
    $.each(search, function(index, value){ 
 
     //Check if the entered string is present in the array of words 
 
     if(value.words.indexOf(str) !== -1){ 
 
     //We found the entered word 
 
     found = true; 
 
     //Display the result linked to the word entered 
 
     $('#result').html(value.result); 
 
     //Exit from the each() method 
 
     return false; 
 
     } 
 
    }); 
 
    //Check if we found our word 
 
    if(!found) 
 
     //Display the error message if you dont find the entered word 
 
     $('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? '); 
 
    } 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="txt"> 
 

 
<p id="result"></p>

+0

這是我們想要的方式。非常感謝!如果您有任何時間,我們將非常感謝您是否可以插入描述每個步驟的註釋。 –

+0

@ h.johan完成,告訴我,如果你明白了一切 – Weedoze

+0

非常感謝。這部分工作就像我們希望的那樣。然而,只有一個關鍵字(在這種情況下,「hey」或「bro」起作用,而不是「Hey bro」)才能起作用,從而消除了通過一個句子得到答案的可能性(例如「你能說忍者?)@weedoze –