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

78
Vistas
Function to add object to array returns Undefined

I have the following code which I try to add some objects to the array with two existing objects through a function but it always returns undefined and I don't know how to solve it.

let compte = {
  iban: "ES79 2100 0813 6101 2345 6789",

  saldo_inicial: 15000,

  operacions: [{
    quantitat: 1200,
    concepte: 'X',
    data_operacio: new Date(Date.now()),
  }, {
    quantitat: -100,
    concepte: 'X',
    data_operacio: new Date(Date.now()),
  }],

  afegir_operacio: function(quantitat, concepte, data_operacio) {
    compte.operacions.push({
      quantitat: quantitat,
      concepte: concepte,
      data_operacio: data_operacio
    });
    console.log(compte.operacions);
  }
}

compte.afegir_operacio({
  quantitat: -100,
  concepte: "Factura",
  data_operacio: "3-10-2021"
});
compte.afegir_operacio({
  quantitat: -50,
  concepte: "Compra"
});

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

0

You get undefined because the data you're trying to add is not what you're passing to the function. Take a look at the corrections. When you do not pass a value for a given property, you'll get undefined for that property unless you define a default value:

let compte = {
        iban: "ES79 2100 0813 6101 2345 6789",
    
        saldo_inicial : 15000,
    
        operacions: [{
            quantitat: 1200,
            concepte: 'X',
            data_operacio: new Date(Date.now()),
        }, {
            quantitat: -100,
            concepte: 'X',
            data_operacio: new Date(Date.now()),
        }],
    
        afegir_operacio: function ({quantitat, concepte, data_operacio = "default_value"}) {
            this.operacions.push({quantitat: quantitat, concepte: concepte, data_operacio: data_operacio});
            console.log(this.operacions);
        }
    }
    
    compte.afegir_operacio({ quantitat: -100 , concepte: "Factura", data_operacio: "3-10-2021" });
    compte.afegir_operacio({ quantitat: -50, concepte: "Compra" });

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