Reputation: 17785
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
Upvotes: 1
Views: 101
Reputation: 236022
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.
Upvotes: 6
Reputation: 47776
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);
Upvotes: 1