Javascript-遍历具有数组属性的对象

时间:2019-04-28 23:52:39

标签: javascript arrays object ecmascript-6

我正在尝试使用JS开发一个简单的BlackJack游戏。这是我的一些代码:

 function card(suit, face) {
    this.suit = suit;
    this.face = face;

    switch (face) {
        case "A":
            this.faceValue = 11;
            break;
        case "J":
        case "Q":
        case "K":
            this.faceValue = 10;
            break;
        default:
            this.faceValue = parseInt(face);
            break;
    }
};

const player = {
    cards: [],
    handValue: 0
}

const dealOneCardToPlayer = () => {     
    tempCard = deck.cards.splice(0, 1);
    player.cards.push(tempCard);
    player.handValue = countHandValue(player.cards);
}

我被countHandValue方法所困,无法获得玩家对象的Cards的faceValue。我尝试了几种类型的for循环,但仍然没有成功。一旦获得faceValue,就可以将其汇总并分配给handValue属性。

const countHandValue = (cardsOnHand) => {    
    for (const key of cardsOnHand) {
        console.log(key.faceValue);
    }

    for (const key in cardsOnHand) {
        console.log(key.faceValue);
    }
}

[已编辑代码]我搜索并找到了这段代码,可以检索到我的faceValue属性,但我相信还有很多额外的代码:

    const countHandValue = (cardsOnHand) => {
    let sum = 0;
    for (var key in cardsOnHand) {
        var arr = cardsOnHand[key];
        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];
            for (var prop in obj) {
                if (prop === "faceValue") {
                    console.log(prop + " = " + obj[prop]);
                    sum = sum + obj[prop];                        
                }                    
            }
        }
    }        
    return sum;
}

2 个答案:

答案 0 :(得分:1)

您可以只使用reduce

const coundHandValue = cards => cards.reduce((acc, { faceValue }) => acc + faceValue, 0);

答案 1 :(得分:1)

请考虑A可以得分为1 11。该程序向您展示了如何处理-

const add = (x = 0, y = 0) =>
  x + y

const sum = (a = []) =>
  a .reduce (add, 0)

const scoreCard = (face = "") =>
  face === "A"
    ? [ 11, 1 ]
: (face === "K") || (face === "Q") || (face === "J")
    ? [ 10 ]
: [ Number (face) ]

const allScores = ([ face = "", ...more ]) =>
  face === ""
    ? [ scoreCard (face) ]
    : allScores (more)
        .flatMap
          ( hand =>
              scoreCard (face) .map (v => [ v, ...hand ])
          )

const scoreHand = (...hand) =>
{ const [ best = "Bust" ] =
    allScores (hand)
      .map (sum)
      .filter (score => score <= 21)
  
  if (best === 21)
    return "Blackjack!"
  else
    return String (best)
}

console .log
  ( scoreHand ("A", "K")                     // Blackjack!
  , scoreHand ("A", "A", "K")                // 12
  , scoreHand ("A", "A", "K", "7")           // 19
  , scoreHand ("J", "4", "K")                // Bust
  , scoreHand ("A", "A", "A", "A", "K", "7") // Blackjack!
  )