我创建了一个简单的对象。我正在尝试在对象上创建一种方法,该方法可以处理一个数组中的数据并将数据推入两个新数组中。由于某些原因,新数据将不会填充两个新数组。当我运行方法john.tipCalc();时 什么都没有推到我的空数组。
let john = {
fullName: "John Smith",
bills: [124, 48, 268, 180, 42],
tips : [],
finalBill : [],
tipCalc: function() {
this.bills.forEach(function(bill) {
let percentage;
if (bill < 50) {
percentage = 0.2;
} else if (bill >= 50 && bill <= 200) {
percentage = 0.15;
} else {
percentage = 0.1;
}
this.tips = bill * percentage;
this.finalBill = bill + bill * percentage;
});
}
};
我想用在tipCalc方法中计算为“提示*百分比”的提示来填充“提示”数组。然后,我要在“ finalBill”数组中填充帐单总额以及按帐单+帐单*百分比计算的小费百分比。
您需要push()
进入tips
。您还需要使用一个箭头功能() => {}
的forEach
,如果你想用this.tips
你的方式:
let john = {
fullName: "John Smith",
bills: [124, 48, 268, 180, 42],
tips : [],
finalBill : 0, // shouldn't this be a single number?
tipCalc: function() {
this.bills.forEach(bill => { // use arrow function
let percentage;
if (bill < 50) {
percentage = 0.2;
} else if (bill >= 50 && bill <= 200) {
percentage = 0.15;
} else {
percentage = 0.1;
}
this.tips.push(bill * percentage); // push()!
this.finalBill += bill * percentage; // add
});
}
};
john.tipCalc()
console.log("Tips", john.tips)
console.log("Final:", john.finalBill )
如果由于某种原因您不能使用箭头功能,则可以将其this
作为最终参数传递给forEach()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句