1

What's wrong with this?

var colours = ['red','green', 'blue']
console.log('blue' in colours); // outputs false

It outputs false, I would have thought it should be trye.

Thanks

asked Mar 21, 2012 at 20:55
1
  • 1
    The problem is that the in operator in JavaScript is not as nice as it is e.g. in Python. Commented Mar 21, 2012 at 20:59

3 Answers 3

6

Since you're dealing with an Array there you can't check for it that way. Arrays offer you the Array.prototype.indexOf method to determine whether or not something is in there:

console.log( colours.indexOf( 'blue' ) > -1 );

Explanation:

Arrays in ECMAscript are just specialized Objects. That means your Array really looks like

colours = {
 0: 'red',
 1: 'green',
 2: 'blue'
};

Since the in operator only checks for object keys, you cannot check for values with it. You indeed could check for if('1' in colours) for instance (which would return true), but that doesn't make much sense. Again, use .indexOf() for Arrays.

Side-note: ECMAscript Harmony (ES.Next, or ES6) will give is the for of loop which instead of keys, enumerates object values. I'm not quite sure if we can use the of operator the same way as in, but it would be quite useful.

answered Mar 21, 2012 at 20:57
Sign up to request clarification or add additional context in comments.

Comments

1

Use colours.indexOf('blue').

answered Mar 21, 2012 at 20:58

Comments

1

This will only work on objects. It checks whether an object has a property.

var colours = { red: 123, green: true, blue: "foo"};;
console.log("blue" in colours);

Use indexOf in modern browsers:

var colours = ['red','green', 'blue'];
console.log(colours.indexOf("blue") != -1);
answered Mar 21, 2012 at 20:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.