Simion Benderschii
Simion Benderschii

Reputation: 47

Javascript says number isn't in array?

var colors={
    red: [1,2,3,4,5,6],
    green: [14,15,16],
    black: [8,9,10,11,12,13],

}

I'm working on a gambling website and this is part of the random prediction code. When i type in console 14 in colors.green it returns false along with any other number in the green array. However any number from red or black returns true with the same console command. Does anybody know why?

Upvotes: 1

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

Using in checks to see if the value is a property name on the object (or anywhere on the object's prototype). For what you're doing, you should use the includes method, which checks whether a value is one of the values of an array:

var colors={
    red: [1,2,3,4,5,6],
    green: [14,15,16],
    black: [8,9,10,11,12,13],
};
console.log(colors.green.includes(14));
console.log('red' in colors);

If you need to support obsolete browsers and can't use a polyfill, you can check to see if the indexOf is -1 instead:

var colors={
    red: [1,2,3,4,5,6],
    green: [14,15,16],
    black: [8,9,10,11,12,13],
};
// any number other than -1 means the element was found:
console.log(colors.green.indexOf(15));
console.log(colors.green.indexOf(999));

Upvotes: 4

Related Questions