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

172
Visualizações
how to push value to array

I have this function

getVal(item){
  var data = [];
  data.push(item);
  console.log(data);
}

the value of the variable item is:

4.9000
6.7000

I want to insert into an array , but the result in my console is this:

4.9000
6.7000

I want the output to be this: [4.9000, 6.7000 ]

Do I have to merge first? Or maybe my push technique is wrong?

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

0

Remove data from getVal scope. here you make a new array for each execution

var data = [];
getVal(item){
  data.push(item);
  console.log(data);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Your logic with push function is right. But the problem is every time the function run, you clear all the previous value.

An alternative solution is to declare it outside or you could run a for loop:

let data = [];
function getVal(item){
  data.push(item);
}
getVal(1)
getVal(2)
  console.log(data);

Run a for loop:

let data = [];

 function getVal(item){
  let data = []  
  for(let i in item){
  data.push(i);
  }
  console.log( data)
}

getVal([1,2,3])

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to move the initialization of data out of the function body. You can avoid the global variable using a closure and an IIFE

const getVal = (() => {
  const data = [];
  return (item) => {
    data.push(item);
    console.log(data);
  }
})();

Example:

const getVal = (() => {
  const data = [];
  return (item) => {
    data.push(item);
    console.log(data);
  }
})();

getVal(1);
getVal(2);

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