gpt4 book ai didi

javascript - 为什么我的方法没有将结果推送到我的阵列?

转载 作者:行者123 更新时间:2023-11-30 09:17:47 25 4
gpt4 key购买 nike

我创建了一个简单的对象。我正在尝试在对象上创建一种方法,该方法操作一个数组中的数据并将数据推送到两个新数组。由于某种原因,新数据不会填充两个新数组。当我运行方法 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 方法中计算为 bill * 百分比的小费。然后我希望“finalBill”数组填充账单总额加上用账单+账单*百分比计算的小费百分比。

最佳答案

您需要push() 进入tips。如果您想按照您的方式使用 this.tips,您还需要在 forEach 中使用箭头函数 () => {}是:

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

关于javascript - 为什么我的方法没有将结果推送到我的阵列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53891898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com