【发布时间】:2019-12-16 05:30:51
【问题描述】:
在下面的代码中,当我控制台calculateTips() 的值时,我收到以下错误
未捕获的类型错误:无法设置未定义的属性“0”
let tipCal = {
bills: [124, 48, 268, 180, 42],
calculateTips: function() {
this.tips = [];
this.finalValue = [];
(this.bills).forEach(function(item, index) {
if (item < 50) {
this.tips[index] = (item * .2);
} else if (item >= 50 && item < 200) {
this.tips[index] = (item * .15);
} else {
this.tips[index] = (item * .1);
}
});
return this.tips;
}
}
我无法理解为什么会出现此错误,因为根据我的说法,我正在做正确的事情。请帮忙。
【问题讨论】:
-
this在您的.forEach函数中没有引用您的对象。您可以改用箭头函数
标签: javascript arrays object foreach