Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if in x [duplicate]

Tags:

javascript

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?

like image 835
Codahk Avatar asked Jun 15 '11 10:06

Codahk


2 Answers

In javascript you can use

if(list.indexOf(x) >= 0) 

P.S.: Only supported in modern browsers.

like image 31
Ash Burlaczenko Avatar answered Oct 05 '22 08:10

Ash Burlaczenko


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.

like image 116
Quentin Avatar answered Oct 05 '22 06:10

Quentin