gpt4 book ai didi

javascript - 我在最后一个函数中的数字旁边得到 NaN

转载 作者:行者123 更新时间:2023-11-28 03:07:35 25 4
gpt4 key购买 nike

var john  = {
name: 'John Smith',
bills: [124,48,268,180,42],
tips : [],
final: [],
calcTips: function(){
for(i = 0; i < this.bills.length;i++){
if(this.bills[i] < 50){
this.tips[i] = this.bills[i] * 0.2;
this.final[i] = this.bills[i] + this.tips[i];
} else if(this.bills[i] >= 50 && this.bills[i] <= 200){
this.tips[i] = this.bills[i] * 0.15;
this.final[i] = this.bills[i] + this.tips[i];
} else{
this.tips[i] = this.bills[i] * 0.1;
this.final[i] = this.bills[i] + this.tips[i];
}
}
}

};

var mark  = {
name: 'Mark Smith',
bills: [77,375,110,45],
tips : [],
final: [],
calcTips: function(){
for(i = 0; i < this.bills.length;i++){
if(this.bills[i] < 100){
this.tips[i] = this.bills[i] * 0.2;
this.final[i] = this.bills[i] + this.tips[i];
} else if(this.bills[i] >= 100 && this.bills[i] <= 300){
this.tips[i] = this.bills[i] * 0.1;
this.final[i] = this.bills[i] + this.tips[i];
} else{
this.tips[i] = this.bills[i] * 0.25;
this.final[i] = this.bills[i] + this.tips[i];
}
}
}

};

function calcAverage(tips){
var sum = 0;
for(i = 0; i < tips.length ; i++){
sum = tips[i] + sum;
}
return sum / tips.length;

}

mark.Average = calcAverage(mark.tips);
john.Average = calcAverage(john.tips);
mark.calcTips();
john.calcTips();
console.log(john);
console.log(mark);

除了平均值之外,函数 calcAverage 返回 NaN。我对其进行了编码,以便它将循环tips数组并将tips加上总和添加到sum变量中。有人可以解释一下这个问题吗?

最佳答案

据我所知,平均小费是在小费实际存在之前计算的。如果您移动上面提示的计算,它应该可以正常工作:

mark.calcTips();
john.calcTips();
mark.Average = calcAverage(mark.tips);
john.Average = calcAverage(john.tips);
console.log(john);
console.log(mark);

关于javascript - 我在最后一个函数中的数字旁边得到 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468807/

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