39

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?

1

3 Answers 3

40

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.

p.s. original answer is from 2011, now it's supported by all browsers in use. https://caniuse.com/?search=indexof

Sign up to request clarification or add additional context in comments.

Comments

20

In javascript you can use

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

p.s. only ancient browsers don't support it

https://caniuse.com/?search=indexof

3 Comments

Only on modern browsers.
@T.J - Point taken. Which browsers don't support this?
I don't know the full list, but it's missing from IE8 and below (yes, really). Microsoft finally added it to IE9. I think the other majors have had it for years, wouldn't know about some of the mobile browsers (Blackberry, etc.) You can check here.
5

in more genric way you can do like this-

//create a custopm function which will check value is in list or not Array.prototype.inArray = function (value) // Returns true if the passed value is found in the // array. Returns false if it is not. { var i; for (i=0; i < this.length; i++) { // Matches identical (===), not just similar (==). if (this[i] === value) { return true; } } return false; }; 

then call this function in this way-

if (myList.inArray('search term')) { document.write("It's in the list!") } 

3 Comments

Why not just use Array.includes?
if (y in list === false) console.log(${y} doesn't exist in [${list}]); else console.log(${y} exist in [${list}]);
if (list.includes(x)) console.log("It's in the list!"); else console.log("It's not in the list!");

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.