所以,我刚刚开始学习Javascript,我遇到的一个问题是根据支付的金额计算提示。这是我的第一次尝试:
var john = {
bills: [124, 48, 268, 180, 42],
calculateTip: function() {
for (var i = 0; i < this.bills.length; i++) {
if (this.bills[i] < 50) {
this.tips[i] = this.bills[i] * 0.2;
} else if (this.bills[i] < 200) {
this.tips[i] = this.bills[i] * 0.15;
} else {
this.tips[i] = this.bills[i] * 0.1;
}
}
return this.tips;
}
};
john.calculateTip();
console.log(john.tips);
但这是我得到的错误:
Uncaught TypeError: Cannot set property '0' of undefined
at Object.calculateTip (script.js:8)
at script.js:17
calculateTip @ script.js:8
(anonymous) @ script.js:17
然后我在对象内部声明了一个空数组:
var john = {
bills: [124, 48, 268, 180, 42],
tips: [],
calculateTip: function() {
for (var i = 0; i < this.bills.length; i++) {
if (this.bills[i] < 50) {
this.tips[i] = this.bills[i] * 0.2;
} else if (this.bills[i] < 200) {
this.tips[i] = this.bills[i] * 0.15;
} else {
this.tips[i] = this.bills[i] * 0.1;
}
}
return this.tips;
}
};
john.calculateTip();
console.log(john.tips);
它运作得很好。
当我在一个对象内部的函数内部而不是一个数组中创建一个普通变量时,我不必事先声明它。数组总是如此,如果有人可以解释错误,我会得到更多?
它只是链接到这样一个事实:在任何声明的JS对象中,您可以引用任何属性名称(您将只有一个未定义的值):
var test = { name: "Hello" }
console.log(test.anything) // Would print undefined
var test2 = {
name: "Hello"
test3 : {}
}
console.log(test2.test3.anything) // Would print undefined
但在您的情况下,您尝试访问不存在的选项卡的特定索引,因此未编制索引
您的错误是指您尝试的第一个作业:
Uncaught TypeError: Cannot set property '0' of undefined
在这一行当i = 0
:
this.tips[i] = this.bills[i] * 0.2;
^
undefined
Then undefined[0] would throw the error
是的,您必须在访问它们之前声明复杂对象。您应该这样做的原因很简单 - 如果未设置值,则每个对象字段都具有值undefined
。在这种情况下,您只是尝试访问导致错误的undefined
值的第一个元素。如果要访问属性为undefined
的子属性,则会引发相同的错误
var a = {
b: '111'
}
a.c.d = '222'
将无法工作,因为属性c
缺失,它的值是undefined
。你应该首先创建属性c
var a = {
b: '111',
c: {}
}
a.c.d = '222'
将工作