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

163
Vistas
Define an array just once and change it without defining it again in JavaScript

I want to define an array in a line of the program, for example, as follows:

var a = [2,5];
//In the next steps, I want to increase the array elements as follows:
a[0] += 2;
a[1] += 2;
//And I want the array to increase intermittently at the output of the program, as follows:
a = [4,7]
a = [6,9]
a = [8,11]
//....

But in reality this does not happen because in the first line of the program, the array is defined again and again.

And the output is always as follows: a = [4,7];

Is there a way to initialize the a array as [2,5] only once?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There are many ways to do this.

  • This is a very simple way if you want to increase it a fixed number of times:
    let a = [2,5];
    for (let i=0;i<5;i++) {
        a=a.map(element=>element+2);
        console.log(a);
    }
  • Using a nested function/closure as shown in Lonnie Best's answer

  • Or you can also use a generator function:

    function * arrayIncreaser(initialArray, num) {
      let a = initialArray;
      while (true) {
        a = a.map(element=>element+num)
        yield a;
      }
    }
    
    const increaser = arrayIncreaser([2,5],2)
    console.log(increaser.next().value);
    console.log(increaser.next().value);
    console.log(increaser.next().value);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Here, I use a closure. The array is created once and modified each time you call increase():

function createIncreaseFunction()
{
  const a = [2,5];
  function increase()
  {
    a[0] += 2;
    a[1] += 2;
    return a;
  }
  return increase;
}
let increase = createIncreaseFunction();
console.log(increase()); // [4,7]
console.log(increase()); // [6,9]
console.log(increase()); // [8,11]

// increase() modifies the values in the array,
// but the same array is returned each time:
console.log(increase() === increase()); // true

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