2017-06-20 22 views
-2

我想創建簡單的chatbot與node.js,但我無法讓if語句工作。我希望if語句在彼此內部,以便用戶只能聊天「你好嗎?」如果他已經說過「你好」。目前我使用的方法根本不起作用。我不知道是否可以有不同的方法來做到這一點,或者我只是做錯了?提前多謝!如何使用if語句在對方內使chatbot(Node.js)

if (message == "Hello") { 
chat.respond(id, "Hi!") 
if (message == "How are you?") { 
chat.respond(id, "Very good sir!") 
} 
} 

回答

0

我覺得你的代碼應該是這樣的:

if (message == "Hello") { 
    chat.response(id, "Hi!") 
} else if (message == "How are you?") { 
    chat.response(id, "Very good sir!") 
} 

與你原來的代碼的問題是,如果message已經是「你好」,那麼它永遠不會平等「?怎麼是你」 ,因此永遠不會執行內部if

如果你想要「你好嗎?」要在「你好」之後,那麼你可以這樣做:

// place this variable in an outer scope 
var receivedHello = false 

// your if statement 
if (message == "Hello") { 
    receivedHello = true 
    chat.response(id, "Hi!") 
} else if (receivedHello && (message == "How are you?")) { 
    chat.response(id, "Very good sir!") 
}