I am trying to make a blackjack game with html/css/javascript, but when I trigger my shuffleDeck function, 1 card in my deck becomes undefined.
Could anyone explain the reasoning for this?
let cardValues = ["A", 1, 2, 3, 4, 5, 6, 7, 8, 9, "J", "Q", "K"];
let cardSuits = ["hearts", "spades", "clubs", "diamonds"];
let deck = new Array();
let players = new Array();
window.onload = function() {
makeDeck();
shuffleDeck(deck);
console.log(deck);
}
function makeDeck() {
deck = new Array();
for (let i = 0; i < cardValues.length; i )
{
for(let j = 0; j < cardSuits.length; j )
{
let weight = parseInt(cardValues[i]);;
if (cardValues[i] == "J" || cardValues[i] == "Q" || cardValues[i] == "K")
{
weight = 10;
} else if (cardValues[i] == "A")
{
weight = 11;
}
let card = {cardValue: cardValues[i], cardSuit: cardSuits[j], cardWeight: weight}
deck.push(card)
}
}
}
function shuffleDeck(deck) {
for (let i = deck.length; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
}
CodePudding user response:
The problem lies in your shuffle loop: You let i = deck.length;
and use i
to access a card position in the deck. But when length is 52, the indexes of the array go from 0 to 51, so you swap undefined into the cards.
This is a very frequent mistake, since the array indices start at 0 not 1.
So to correct this, simply substract one to your length, or start at 0, while i<length.
CodePudding user response:
Like multiple people have already mentioned, your shuffle loop needs to start from deck.length - 1
:
function shuffleDeck(deck) {
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
}
let cardValues = ["A", 1, 2, 3, 4, 5, 6, 7, 8, 9, "J", "Q", "K"];
let cardSuits = ["hearts", "spades", "clubs", "diamonds"];
let deck = new Array();
let players = new Array();
window.onload = function() {
makeDeck();
shuffleDeck(deck);
console.log(deck);
}
function makeDeck() {
deck = new Array();
for (let i = 0; i < cardValues.length; i )
{
for(let j = 0; j < cardSuits.length; j )
{
let weight = parseInt(cardValues[i]);;
if (cardValues[i] == "J" || cardValues[i] == "Q" || cardValues[i] == "K")
{
weight = 10;
} else if (cardValues[i] == "A")
{
weight = 11;
}
let card = {cardValue: cardValues[i], cardSuit: cardSuits[j], cardWeight: weight}
deck.push(card)
}
}
}
function shuffleDeck(deck) {
for (let i = deck.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i 1));
[deck[i], deck[j]] = [deck[j], deck[i]];
}
}