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

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

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 Denunciar

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 Denunciar

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