So I built this function for a card game, for the "deal card" feature:
const dealCards = () => {
for(let i = 0; i < users.length; i++) {
let card = cards.pop()
playerHands[i].hand.push(card)
}
}
The main purpose of it is to insert an object into the
hand: []
element of playerHands
Player Hands is structured like this:
0: {id: 0, user: 'Player 1', hand: Array(0), score: 0}
1: {id: 0.9801915170560507, user: 'Player 2', hand: Array(0), score: 0}
2: {id: 0.0006669572315951555, user: 'Player 3', hand: Array(0), score: 0}
3: {id: 0.5767750038678146, user: 'Player 4', hand: Array(0), score: 0}
4: {id: 0.6448035494497826, user: 'Player 5', hand: Array(0), score: 0}
and the element im trying to push into hand like this :
{suits: '♦', value: '9'}
The issue I'm having is that instead of running through the for loop and inserting a new element for every user ( based on the [i] index), it insert this for every user:
0: {suits: '♦', value: 'K'}
1: {suits: '♦', value: 'Q'}
2: {suits: '♦', value: 'B'}
3: {suits: '♦', value: '10'}
4: {suits: '♦', value: '9'}
Here's an example:
Let's say there are 5 players.
The loop runs 5 times.
It increments i like it's supposed to.
But for some reason, instead of having one different card for every user, I get all 5 cards from the pop for every user.
So every user gets the same 5 cards in their hand
Here's an example of what I see in the browser:
I'm at a loss of why it is doing this, does anyone have an idea?
I don't know the users array, but assuming it has the same length like playerHands array then I use the playerHands array for iteration.
const dealCards = () => {
for( let i = 0; i < playerHands.length; i++ ) {
let card = cards.pop()
playerHands[i].hand.push(card)
}
}
let playerHands = [
{id: 0, user: 'Player 1', hand: Array(0), score: 0},
{id: 0.9801915170560507, user: 'Player 2', hand: Array(0), score: 0},
{id: 0.0006669572315951555, user: 'Player 3', hand: Array(0), score: 0},
{id: 0.5767750038678146, user: 'Player 4', hand: Array(0), score: 0},
{id: 0.6448035494497826, user: 'Player 5', hand: Array(0), score: 0}
]
let cards = [
{suits: '♦', value: 'K'},
{suits: '♦', value: 'Q'},
{suits: '♦', value: 'B'},
{suits: '♦', value: '10'},
{suits: '♦', value: '9'}
]
dealCards()
console.log(playerHands) // to show the result