这是一个基本的 JavaScript 代码,用于计算给定值的“提示”。我在这里做错了什么吗?它给了我 null
数组或 NaN
而不是我的数组内容。
var john = {
fullName: 'john smith',
bills: [124, 48, 32, 268, 180, 42],
calcTips: function () {
this.tips = [0];
this.finalvalue = [0];
for (var i = 0; i < this.bills.length; i += 1) {
var percentage;
if (this.bills[i] < 50) {
percentage: .2;
}
else if (this.bills[i] >= 50 && this.bills[i] < 200) {
percentage: .15;
}
else {
percentage: .1;
}
this.tips[i] = this.bills[i] * percentage;
this.finalvalue[i] = this.bills[i] + this.bills[i] * percentage;
}
}
}
最佳答案
假设 tips
数组中的值已等于 bills
数组中的值数量,并更新 tips 中的相应值
(我可能会补充,这是错误的。稍后介绍)。
但是,由于您仅使用一个值 0 初始化 tips
,因此循环在第一次迭代之后没有任何内容可更新。
相反,我建议:
var john = {
fullName: 'john smith',
bills: [124, 48, 32, 268, 180, 42],
calcTips: function() {
/* I'm assuming you initialized these with one value of 0 because you're doing
a calculation later using these, so we'll leave them be */
this.tips = [0];
this.finalvalue = [0];
for ( var i = 0; i < this.bills.length; i+= 1 ) {
var percentage;
/* Reassigning variables requires the equals sign (=) rather than
a colon (:) */
if (this.bills[i] < 50) {
percentage = .2;
} else if (this.bills[i] >= 50 && this.bills[i] < 200 ) {
percentage = .15;
} else {
percentage = .1;
}
/* If i is 0, only update the first value of tips (using splice()), past
that, push in a new value */
if (i === 0) {
this.tips.splice(i, 1, this.bills[i] * percentage ;
} else {
this.tips.push(this.bills[i] * percentage);
}
this.finalvalue[i] = this.bills[i] + this.bills[i] * percentage;
}
}
}
关于javascript - 它给出 NaN 而不是数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130612/