shuffling array javascript
- by Dennis Callanan
<!doctype html>
<html lang="en">
<head>
<meta charset="utf=8" />
<title>Blackjack</title>
<link rel="stylesheet" href="blackjack.css" />
<script type="text/javascript">
var H2 = 2; var S2 = 2; var D2 = 2; var C2 = 2;
var H3 = 3; var S3 = 3; var D3 = 3; var C3 = 3;
var deck = new Array(H2, S2, D2, C2, H3, S3, D3, C3);
var new_deck = new Array();
var r;
document.write("deck = ")
for (r =0; r<deck.length; r++){
document.write(deck[r]);
}
document.write("</br>")
document.write("new deck = ")
for (r=0; r<new_deck.length; r++){
document.write(new_deck[r]);
}
document.write("</br>")
for (r=0;r<deck.length;r++){
var randomindex = Math.floor(Math.random()*deck.length);
new_deck.push(randomindex)
deck.pop(randomindex)
}
document.write("deck = ")
for (r =0; r<deck.length; r++){
document.write(deck[r]);
}
document.write("</br>")
document.write("new deck = ")
for (r=0; r<new_deck.length; r++){
document.write(new_deck[r]);
}
document.write("</br>")
</script>
</head>
<body>
</body>
</html>
Obviously this isn't the full Blackjack game here. It's just a test to see if shuffling the array works by printing the contents of both decks (arrays) before and after the shuffle.
I'm only using 8 cards at the moment, 4 2's and 4 3's.
What I am getting from this is:
deck = 22223333
new deck =
deck = 2222
new deck = 7502
What I'm hoping to get is:
deck = 22223333
new deck =
deck =
new deck = 23232323 (or any of the 8 numbers, generated randomly)
So it should be shuffling those 8 cards, what am I doing wrong?
I'm only new to javascript but I've used some python before. I've done something similar in python and worked perfectly, but I'm not sure what's wrong here.
Thanks for any answers in advance!!