简体   繁体   中英

checking for string element in javascript array

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

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.

使用colours.indexOf('blue')

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM