Alex Rivera | Logout

Using an array through a switch() statement in Javascript

Asked 2013-07-23T18:26:34.113
15

I'm trying to develop a simplified poker game through Javascript. I've listed all possible card combinations a given player might have in its hand ordered by its value, like this:

switch(sortedHand)
{           
 //Pair
     case [1,1,4,3,2]: sortedHand.push(1,"Pair"); break;
     case [1,1,5,3,2]: sortedHand.push(2,"Pair"); break; 
     case [1,1,5,4,2]: sortedHand.push(3,"Pair"); break;
     case [1,1,5,4,3]: sortedHand.push(4,"Pair"); break;
     case [1,1,6,3,2]: sortedHand.push(5,"Pair"); break;
     case [1,1,6,4,2]: sortedHand.push(6,"Pair"); break;
     case [1,1,6,4,3]: sortedHand.push(7,"Pair"); break;
     case [1,1,6,5,2]: sortedHand.push(8,"Pair"); break;
     case [1,1,6,5,3]: sortedHand.push(9,"Pair"); break;
     case [1,1,6,5,4]: sortedHand.push(10,"Pair"); break;

Even though the "sortedHand" array stores values succesfully (as I've seen through console.log), the switch() statement always returns the default case, and everyone gets an straight flush. I fear this is a matter of the literal approach I've used to declare possible array values to be compared with the whole of "sortedHand", but I don't know any better. Is it even possible to use switch() in such a manner?

Edit
Report

1 Answer

1

That will not quite work as you have it, but you can use sortedHand.join(',') and compare it with [1,1,1,2,5].join(',') which will compare the two arrays and should be true if their contents were the exact same (Be careful with numbers typed as strings!) To be fair, though, I can't imagine why you would design your logic like that. Even a simple card game has hundreds of thousands of possible hands. You might do better using underscore.js's collection managing functions as it will be simpler, and just a better practice.

answered 2013-07-23T18:32:54.713

Your Answer