gpt4 book ai didi

javascript - 函数 calcAverage 怎么可能返回(提示)?

转载 作者:行者123 更新时间:2023-11-30 20:01:15 24 4
gpt4 key购买 nike

我正在学习 Udemy 上的类(class),但我无法理解下面的一行代码。我想知道这怎么可能 代码底部的函数 calcAverage(tips) 可以访问对象 john 和 mark 的属性提示。

var john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];

for (var i = 0; i < this.bills.length; i++) {
// Determine percentage based on tipping rules
var percentage;
var bill = this.bills[i];

if (bill < 50) {
percentage = .2;
} else if (bill >= 50 && bill < 200) {
percentage = .15;
} else {
percentage = .1;
}

// Add results to the corresponing arrays
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}

var mark = {
fullName: 'Mark Miller',
bills: [77, 475, 110, 45],
calcTips: function() {
this.tips = [];
this.finalValues = [];

for (var i = 0; i < this.bills.length; i++) {
// Determine percentage based on tipping rules
var percentage;
var bill = this.bills[i];

if (bill < 100) {
percentage = .2;
} else if (bill >= 100 && bill < 300) {
percentage = .1;
} else {
percentage = .25;
}

// Add results to the corresponing arrays
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}

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

最佳答案

calcAverage 对对象 markjohn 一无所知。它只是一个需要数组作为参数的函数。它将计算传入数组的平均值:

var mark = {
fullName: 'Mark Miller',
bills: [77, 475, 110, 45],
calcTips: function() {
this.tips = [];
this.finalValues = [];

for (var i = 0; i < this.bills.length; i++) {
// Determine percentage based on tipping rules
var percentage;
var bill = this.bills[i];

if (bill < 100) {
percentage = .2;
} else if (bill >= 100 && bill < 300) {
percentage = .1;
} else {
percentage = .25;
}

// Add results to the corresponing arrays
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}

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

mark.calcTips() // calculates tips and store as tips property

// pass mark.tips into function
console.log("Mark's tip average:", calcAverage(mark.tips))

关于javascript - 函数 calcAverage 怎么可能返回(提示)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53355782/

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