所以,我刚开始学习 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
关于javascript - 在使用它之前,我是否必须在 Javascript 中的对象内部声明一个空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807419/