Possible Duplicates:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)
I usually program in python but have recently started to learn JavaScript.
In python this is a perfectly valid if statement:
list = [1,2,3,4] x = 3 if x in list: print "It's in the list!" else: print "It's not in the list!"
but I have had poblems doing the same thing in Javascript.
How do you check if x is in list y in JavaScript?
In javascript you can use
if(list.indexOf(x) >= 0)
P.S.: Only supported in modern browsers.
Use indexOf which was introduced in JS 1.6. You will need to use the code listed under "Compatibility" on that page to add support for browsers which don't implement that version of JS.
JavaScript does have an in
operator, but it tests for keys and not values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With