Home > Back-end >  I want a loop where each time it is called by a function the I value stays the same
I want a loop where each time it is called by a function the I value stays the same

Time:01-02

I am attempting to write a dealer function for a card game, I want the function to keep its i value each time its called, so that that the card pile( player1Deck and player2Deck) gets smaller and smaller till empty. currently the i value looks like it will reset each time the function is called how can I stop this. I am very new to all of this.

function dealOut(){
    for (let i = 0; i < player1DeckHandcells.length; i  ) {
        const cell = player1DeckHandcells[i];
        cell.appendChild(player1Deck.cards[i].getHTML)
    }
    for (let i = 0; i < player2DeckHandcells.length; i  ) {
        const cell = player2DeckHandcells[i];
        cell.appendChild(player2Deck.cards[i].getHTML)
    }
}

More information

Each dealout call should make i increase by 7. this means we are on the 8th "card"(player1Deck.cards[i].getHTML and player2Deck.cards[i].getHTML) in the "deck"( player1Deck and player2Deck)and there should be a total of 28 cards with 21 left to go. I want the i value to count through these "cards", so it doesn't just repeat the first 7 every time dealout is called.

CodePudding user response:

You can use a closure (a function that keeps a copy of the outer variables). We can use that function for dealOut. Note: arrays are zero-indexed so i starts at 0 not 1.

function loop() {

  // Maintain a count
  let count = 0;
  
  // Return a function that we actually use
  // when we call dealOut. This carries a copy
  // of count with it when it's returned that we
  // can update
  return function () {
    
    const arr = [];

    // Set i to count, and increase until
    // i ia count   7
    for (let i = count; i < count   7; i  ) {
      arr.push(i);
    }
    
    console.log(arr.join(' '));
    
    // Finally increase count by 7
    count  = 7;
  }
}

const dealOut = loop();

dealOut();
dealOut();
dealOut();
dealOut();

  • Related