1

Hey again (on a roll today).

In jQuery/Javascript is there a way of effectively having this:

var myArray = [ 'zero', 'one', 'two', 'three', 'four', 'five' ];

//get input from user
if (inputFromUser == anythingInArray) {
  alert("it's possible!);
}
Barrie Reader
  • 10,647
  • 11
  • 71
  • 139

3 Answers3

3

is it this?

http://api.jquery.com/jQuery.inArray/

bharling
  • 2,800
  • 1
  • 18
  • 25
  • Not sure why this was voted down - perfectly relevant - someone didn't like the fact I accepted this answer maybe? – Barrie Reader Sep 15 '10 at 10:07
  • 1
    @Neurofluxation - People tend to vote on the quality of an answer and if a bad quality answer is upvoted, it's sometimes downvoted. It wasn't I who downvoted, however just copying and pasting a link is generally frowned upon within the community. StackOverflow is about writing quality answers, not just doing a 5 second google search and pasting a link. Take @jAndy's answer - He's put a lot of effort in and even given you a non jQuery answer as well. Within my answer, I provided the link as within this accepted answer, but also gave an example of it's use. – djdd87 Sep 15 '10 at 10:28
  • 1
    @Neurofluxation - If you'd looked at and understood @jAndy answer and my answer, then you wouldn't have had to ask this question http://stackoverflow.com/questions/3716656/creating-a-fake-ai-chat-program/3716682#3716682 would you? – djdd87 Sep 15 '10 at 10:29
  • I understand **all** of your opinions but at the end of the day, bharling helped me out... So he got the points, I can't get much fairer than that... I'm not going to take the points off and give someone else them because they put a different answer afterward.. – Barrie Reader Sep 15 '10 at 14:40
2

You can use inArray:

var result = $.inArray(inputFromUser, myArray);
if (result >= 0)
{
   alert('Result found at index ' + result);
}
djdd87
  • 67,346
  • 27
  • 156
  • 195
2

jQuery: $.inArray()

if($.inArray('one', myArray) > -1)  {}

If you need to do it without jQuery, you can use the Array.prototype.indexOf method like

if(myArray.indexOf('one')) {}

That is restricted to ECMAscript Edition 5. If a browser doesn't support that do it the classic route:

for(var i = 0, len = myArray.length; i < len; i++) {
   if(myArray[i] === 'one') {}
}

Ref.: $.inArray()

jAndy
  • 231,737
  • 57
  • 305
  • 359