Home > Software design >  Function to add object to array returns Undefined
Function to add object to array returns Undefined

Time:12-10

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"
});

CodePudding user response:

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" });

  • Related