Skip to content Skip to sidebar Skip to footer

Simplifying This Javascript-switch

I would like some advice on how to slim down this switch: switch (lotUser | winningLot) { case lotUser === winningLot[0]: case lotUser === winningLot[1]: ca

Solution 1:

What about Array.prototype.indexOf()?

if (winnedLot.indexOf(lotUser) !== -1) {
  console.log("Won!");
}
else {
  console.log("Lost!");
}

It searches the array for the first occurrence of the value stored in lotUser and returns its respective index.

Since you do not need to count the occurrences, this should be the best way.


If you want to count them, use a loop:

var count = 0;

for (var i=0, len=winnedLot.length; i<len; i++) {
  if (winnedLot[i] === lotUser) {
    count++;
  }
}

Solution 2:

You can simply use indexOf:

if(winningLot.indexOf(lotUser) >= 0) {
    ...
} else {
    ...
}

Solution 3:

Well for starters you're using switch incorrectly. The value to compare goes in the switch(...) part, and the possible values are listed by each case ...:

Anyway, that aside, all you want is to check if lotUser is in the winnendLot array. Easy:

// assuming supporting browser:if( winnendLot.indexOf(lotUser) > -1) console.log("You win!");

// full browser support:var winner = false, l = winnendLot.length, i;
for( i=0; i<l; i++) {
    if( winnendLot[i] === lotUser) {
        winner = true;
        break;
    }
}
if( winner) console.log("You won!");

Post a Comment for "Simplifying This Javascript-switch"