Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda