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

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

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 Relatório

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 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