Using an array through a switch() statement in Javascript

前端 未结 6 2088
野的像风
野的像风 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-01 23:54

    You can try switching on a textual representation of the array.

    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;
        // etc.
    }
    

    As an alternative to specifying every case directly, perhaps build a function dispatch table using an object and get rid of the switch entirely.

    var dispatch = {};
    
    // Build the table however you'd like, for your application
    for (var i = 0; i < 10; i++) {
        (function(i) {
            var hand = ...; // Add your hand logic here
            dispatch[hand] = function() { sortedHand.push(i, "Pair"); };
        })(i);
    }
    
    // Execute your routine
    dispatch[sortedHand.join(' ')]();
    

提交回复
热议问题