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

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

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