2014-06-08 48 views
0

在下面的代码中,我希望在控制台中的函数消息日志中记录相应的消息响应,并且如果它不在数组消息中记录“我没有完全理解”记录消息的相应响应?

意思是像

消息(“你好”)将登录“你好”,因为两者有2

这里是我的代码索引,我知道那是遥远,但由于

function message(text) { 
       messages = ['Hello', 'hello', 'Hi', 'hi']; 
       responses = ['Hi', 'Hi', 'Hello', 'Hello']; 
       msgKnown = jQuery.inArray(text, arr); 
       if (!msgKnown) { 
        console.log("I didn't quite catch that"); 
       } 
       else { 
        console.log(msgKnown); 
       } 
      } 

回答

1

你不是那样。他们将有2索引,因为这将使其第三一个(记住它从0开始。)

JSFIDDLE感谢@badAdviceGuy

我认为这是你在找什么..

function message(text) { 
    messages = ['Hello', 'hello', 'Hi', 'hi']; 
    responses = ['Hi', 'Hi', 'Hello', 'Hello']; 
    msgKnown = jQuery.inArray(text, messages); // <----- I modified this 
    if (!msgKnown) { 
     console.log("I didn't quite catch that"); 
    } 
    else { 
     console.log(responses[msgKnown]); // <---- I modified this 
    } 
} 

message("Hi"); // will output "Hello" 
+1

打我吧,这里是小提琴展示该解决方案的工作[http://jsfiddle.net/GGvz2/](http://jsfiddle.net/GGvz2/)。 @Sam,你在调用数组'arr'而不是'messages'。 – badAdviceGuy

+0

感谢@badAdviceGuy我会将你的jsfiddle添加到我的答案中。 –

+0

工程,除了它说未定义,而不是我没有抓到那 – Sam