我有以下代碼,我嘗試通過函式將一些物件添加到具有兩個現有物件的陣列中,但它總是回傳 undefined 并且我不知道如何解決它。
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"
});
uj5u.com熱心網友回復:
你得到undefined是因為你試圖添加的資料不是你傳遞給函式的。看看更正。當您沒有為給定屬性傳遞值時,undefined除非您定義一個default值,否則您將獲得該屬性:
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" });
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377959.html
標籤:javascript 数组 目的 推
上一篇:從Python中的矩陣中洗掉空格
下一篇:java替代使用嵌套for回圈
