gpt4 book ai didi

JavaScript 问题。我正在学习 for 循环和数组如何与方法一起工作,不知道为什么我在控制台中收到 NAN 消息

转载 作者:行者123 更新时间:2023-12-01 00:18:38 26 4
gpt4 key购买 nike

到目前为止,这是我整理的代码,然后是我遇到的错误。

var johnFamily;

johnFamily = {

tipCalc: function() {

var percentage;

johnFamily.fullName = 'John Smith';

johnFamily.bills = [124, 48, 268, 180, 42];

johnFamily.tips = [];
johnFamily.totalBills = [];

for (var i = 0; i < johnFamily.bills.length; i++) {

if (johnFamily.bills[i] < 50) {
percentage = .2;
} else if (johnFamily.bills[i] > 50 && johnFamily.bills[i] < 200) {
percentage = .15;
} else if (johnFamily.bills[i] > 200) {
percentage = .1;
} else {
console.log(johnFamily.fullName + ' ' + 'did not leave a tip.');
}

johnFamily.tips[i] = johnFamily.bills * percentage;
johnFamily.totalBills[i] = johnFamily.bills + johnFamily.bills * percentage;
}
}
};

johnFamily.tipCalc();
console.log(johnFamily);

但是,这就是我将其记录到控制台时得到的结果

tips: (5) [NaN, NaN, NaN, NaN, NaN]

totalBills: (5) ["124,48,268,180,42NaN", "124,48,268,180,42NaN", "124,48,268,180,42NaN", "124,48,268,180,42NaN", "124,48,268,180,42NaN"]

它应该创建新属性并通过该方法向它们添加值。

最佳答案

这就是你的问题

johnFamily.bills * percentage;

johnFamily.bills 是一个数组,数组乘以数字没有任何意义,因此您得到 NaN。您可能打算这样做,以便计算特定账单的特定时间。

johnFamily.bills[i] * percentage;

关于JavaScript 问题。我正在学习 for 循环和数组如何与方法一起工作,不知道为什么我在控制台中收到 NAN 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587041/

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