views:

37

answers:

4

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!);
}
+3  A: 

is it this?

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

bharling
Excellent, I will accept when SO lets me
Neurofluxation
Not sure why this was voted down - perfectly relevant - someone didn't like the fact I accepted this answer maybe?
Neurofluxation
@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.
GenericTypeTea
@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?
GenericTypeTea
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..
Neurofluxation
+1  A: 

You can use inArray:

var result = $.inArray(inputFromUser, myArray);
if (result >= 0)
{
   alert('Result found at index ' + result);
}
GenericTypeTea
+1  A: 

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