0

出于某种原因,第二个for循环从 1 开始。我确实意识到第一个for循环i从 1 开始。本来就是这样。然而,即使j for循环说从 0 开始,它仍然从 1 开始。

var findWinners = function (playersRay) {
    var players = playersRay;
    var results = new Array();

    //getdealers dealers hand and info
    var dealerHand = players[0]
    var dealerScore = dealerHand.getScore()
    var dealerBust = dealerScore > 21 ? true : false;

    //loops through all players; skips dealer (array position 0)
    var numPlayers = players.length;
    for (var i=1; i<numPlayers; i++) {
            //loops through all the players hands.
            //player might have more than 1 hand if he splits his cards
        var player = players[i];
        var numHands = player.length;
        results[i] = new Array();

        for (var j=0; j<numHands; j++)
            var handScore = player[j].getScore();

            if (handScore > 21) {
                results[i][j] = false;              
            }
            else if (dealerScore > 21) {
                results[i][j] = true;
            }
            else if (handScore > dealerScore) {
                results[i][j] = true;
            }
            else {
                results[i][j] = false;
            }
    }
    return results;
}

它返回这个:[undefined, [undefined, true]]

它应该返回这个:[undefined, [true]]

以防万一你想知道。一个示例playersRay是: [Object, [Object]]
该对象具有关于庄家或玩家的二十一点手的信息。

完整代码链接:https ://docs.google.com/open?id=0BxvwY0fUFc3aMTdTOXU0b0ttamM

4

1 回答 1

1

在 Javascript 中,当您省略语句周围的花括号时,它只运行第一行。当我怀疑只有两个时,这种行为似乎只省略了第一个索引。因此,如果您添加更多进行迭代,您应该注意到它实际上只是在运行最后一个索引。

例如:

for (var i = 0; i < 10; i++)
    console.log('First line: ', i);

    console.log('Second line: ', i);

http://jsfiddle.net/MMQD8/

给出:

First line: 0
First line: 1
First line: 2
First line: 3
First line: 4
First line: 5
First line: 6
First line: 7
First line: 8
First line: 9
Second line: 10

MDN是这样解释的

陈述

只要条件评估为真,就会执行的语句。要在循环中执行多个语句,请使用块语句 ({ ... }) 对这些语句进行分组。

于 2012-09-03T17:28:52.130 回答