3

I am creating a blackjack game where my deck consists of objects(cardname: value) within an array.

I am wondering if there is a function for javascript objects where I can get an objects value (in my case, the numeric score each card is worth) without having to name the key (ex: "aced")?

Please refer to my code below, specifically in the for loop; I don't know what to replace "myHand[card[value]]" with.

Thanks

function shuffle(array) {
  var m = array.length, t, i;
  // While there remain elements to shuffle…
  while (m) {
    i = Math.floor(Math.random() * m--);
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array;
}

var deck = [{"aced": 11}, {"twod": 2}, {"threed": 3}, {"fourd": 4}, {"fived": 5}, {"sixd":6}, {"sevend": 7}, {"eightd": 8}, {"nined": 9}, {"tend": 10}, {"jackd": 10}, {"queend": 10}, {"kingd": 10},
{"acec": 11}, {"twoc": 2}, {"threec": 3}, {"fourc": 4}, {"fivec": 5}, {"sixc":6}, {"sevenc": 7}, {"eightc": 8}, {"ninec": 9}, {"tenc": 10}, {"jackc": 10}, {"queenc": 10}, {"kingc": 10},
{"aceh": 11}, {"twoh": 2}, {"threeh": 3}, {"fourh": 4}, {"fiveh": 5}, {"sixh":6}, {"sevenh": 7}, {"eighth": 8}, {"nineh": 9}, {"tenh": 10}, {"jackh": 10}, {"queenh": 10}, {"kingh": 10},
{"aces": 11}, {"twos": 2}, {"threes": 3}, {"fours": 4}, {"fives": 5}, {"sixs":6}, {"sevens": 7}, {"eights": 8}, {"nines": 9}, {"tens": 10}, {"jacks": 10}, {"queens": 10}, {"kings": 10}];

shuffle(deck);

function userHand() {
    var myHand = [deck.pop(), deck.pop()];
}

function countScore(myHand) {
    var total = 0;
    for (var card in myHand) {
        total += myHand[card[value]];
    }
}
4
  • If you don't want keys, why not make it a simple array? Commented Aug 1, 2013 at 19:58
  • 1
    If you don't know what they keys will be, then you shouldn't be using key/value pairs. Use Arrays, like ["aced", 11]. Then you can use numeric indices. Or make your objects more complex, like {card:"aced",value:11} Commented Aug 1, 2013 at 19:59
  • 1
    It'd be much easier if you had a better card data model, like { card: "aced", value: 11 } Commented Aug 1, 2013 at 19:59
  • actually now that you mention it, an array within an array seems more logical Commented Aug 1, 2013 at 20:00

1 Answer 1

3

You could potentially change your array, if you're not too far in to this. so rather than having each card be

{'name': value}

you could have each card be

{'type': name, 'value': number}

for instance, to have a 3 of hearts:

{'type': threeh, 'value': 3}.

then, you could access the value by

myHand[card.value]

and the name by

myHand[card.type]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.