-1

I want to check if my var is in my array (a table). Here my code that doesn't work...

var color;
if(roll == green){
    color = "green";
}
else if(red.contains(roll)){
    color = "red";
}
else if(black.contains(roll)){
    color = "black";
}

Here my tables and my roll is sure between 0 and 14

var green = 0;
var red = [1, 3, 5, 7, 9, 11, 13];
var black = [2, 4, 6, 8, 10, 12, 14];
Xcodian Solangi
  • 2,342
  • 5
  • 24
  • 52
TheBlackDev_
  • 93
  • 10
  • I believe this question was answered at https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript – Stanislav Mekhonoshin Oct 14 '17 at 18:26
  • This looks like a perfect use of a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instead of an array since it's trivial to set if something is in a Set (that is its main purpose in life). – jfriend00 Oct 14 '17 at 19:00
  • I believe you are looking for `Array.prototype.includes()`, there is not an `Array.prototype.contains()` method in JavaScript. Try `if(red.includes(roll)){...}` – A-yon Lee Oct 15 '17 at 01:40

1 Answers1

0

Well, the basic approach on the arrays is finding the index of the variable. I'm assuming that you know roll will be a integer number, since you don't show where that comes from. If it might be a string (e.g. if it's coming from an HTML input element of some kind), you'll need to use parseInt() to cast it.

if (roll === 0) {
  color = 'green';
} else if (red.indexOf(roll) !== -1) {
  color = 'red';
} else if (black.indexOf(roll) !== -1) {
  color = 'black';
}

Though to be honest, I'd consider structuring things differently depending on what my goals were.

Paul
  • 35,689
  • 11
  • 93
  • 122
  • Thanks a lot, my var "roll" is an integer its a random value between 0 à 14 :) thanks one more time have a nice night – TheBlackDev_ Oct 14 '17 at 18:22