-1

How do you check if an array contains a value, for example whether or not "hello" is in the array.

  var Greetings = ["hello", "hey", "hi", "sup"];

How would I structure the If statement to check the array. I had previously wrote

  if ("hello" == Greetings[]) { // greeting
  //runs succsessfully
  }

This of course does not work.

tecksup
  • 51
  • 1
  • 13
  • 1
    Possible duplicate of [How do I check if an array includes an object in JavaScript?](http://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – Sebastian Simon Apr 09 '16 at 19:53
  • Don't understand what you're asking for? Do you want to check if a value/string is in the array? – IsraGab Apr 09 '16 at 19:55
  • @IsraGab yes i need to check if the user input contains any of the values in the Greetings array – tecksup Apr 09 '16 at 19:59
  • If so, I think @NiettheDarkAbsol gave you the answer – IsraGab Apr 09 '16 at 20:02

2 Answers2

1

@NiettheDarkAbsol gave exactly what i was looking for.

I used the indexOf() in my code to get it working the way i was looking for.

    if (Greetings.indexOf(messageArray[0]) != -1) { // greeting
    kline.speakAloud("Hello");
    kline.speakText("Hello.");
}

the indexOf gives out a negative 1 integer if the input is not in the array. any of the strings in my array work to run this statement.

Thanks!

tecksup
  • 51
  • 1
  • 13
-1

jQuery offers $.inArray, which is functionally equivalent to Array#indexOf.

Aatif Bandey
  • 1,193
  • 11
  • 14
  • Please do not answer questions that are obvious duplicates. – Jared Smith Apr 09 '16 at 20:01
  • @JaredSmith Who is my question duplicating? if it is a duplicate i would love to know and will gladly use that to answer my question. – tecksup Apr 09 '16 at 20:04
  • @tecksup I wrote that comment *after* Xufox flagged this as a dupe. Duplicate flags always contain a link to the question this one is suspected to be a duplicate of. See comments on your question. And the fact that your question was answered by a 9 character comment should clue you to the fact that you ***should have done a simple google search or two before posting here and cluttering the site.*** – Jared Smith Apr 11 '16 at 13:20