Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
I want a loop where each time it is called by a function the I value stays the same

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!