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

324
Visualizações
How to increment a variable on calling a function in javascript?

I'm trying to store the value of i into a.

function sequence(i,a) {
  
  i=a;
  
  if (i==1) {
    i++;
    return strings[i]
  }
  
  else  {
    i=0;
    i++;
    a=i;
    return strings[i]
  }
  
  
};

strings is an array where I have stored five objects. When I call the function first time it enters else block, and then it enters else block second time as well. Is there a way to make the value of a=1 in the first attempt, and make it inter the if block.

I also tried declaring i=0 outside the function, and using just i++. But everytime the function is called, i becomes 0.

It would be great if we don't require 2 variables at all and are able to store and increment the value of i.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a closure (basically a function that's returned from another one but that keeps track of the variables in its outer scope without making them global.)

// Simple array
const arr = [1, 2, 3, 4, 5];

// A button and a function that returns a new function
// (the closure) as the listener.
// Pass in the array of things to it
const button = document.querySelector('button');
button.addEventListener('click', handleClick(arr), false);

// The function accepts the array of things,
// and initialises the array count
function handleClick(arr, index = 0) {

  // And we return a function that acts as the
  // listener when the button is clicked. It increments
  // the value until it hits the end of the array, and
  // then starts again. The benefit of the closure is that
  // it keeps a note of `index` so you don't have to
  return function () {
    console.log(arr[index]);
    if (index === arr.length - 1) {
      index = 0;
    } else {
      index++;
    }
  }

}
<button>Next</button>

about 4 years ago · Juan Pablo Isaza 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