Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

322
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda