Using an array through a switch() statement in Javascript

前端 未结 6 2087
野的像风
野的像风 2021-01-01 23:28

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, li

6条回答
  •  醉酒成梦
    2021-01-02 00:04

    the switch() statement always returns the default case

    That's because the comparison doesn't check the array contents, but the array object itself. Objects are considered equal by their identity, so nothing will be equal to an object instantiated by a literal.

    Is it even possible to use switch() in such a manner?

    Yes, one can use objects in switch statements, but you would have to use references in the cases. Not applicable to your problem.

    In your case, I'd suggest a stringification:

    switch(sortedHand.join())
    {           
     //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;
    

    but I guess there's an even better, arithmetic solution to detect the patterns you're after. That would be shorter and faster, but I'm not sure what exactly this snippet is supposed to do.

提交回复
热议问题