const list =[ // a 班在今年的第1周打扫了3次卫生 { name :' a 班', count :3, week :1},{ name :' b 班', count :4, week :1},{ name :' c 班', count :5, week :2},{ name :' a 班', count :3, week :3},{ name :' b 班', count :4, week :3}求各班级打扫卫生的总数,在打扫卫生的周里,平均每周打扫了几次
时间: 2024-04-10 14:34:29 浏览: 57
根据给定的列表,我们可以使用 JavaScript 来计算各班级打扫卫生的总数和平均每周打扫次数。下面是相应的代码:
```javascript
const list = [
{ name: 'a班', count: 3, week: 1 },
{ name: 'b班', count: 4, week: 1 },
{ name: 'c班', count: 5, week: 2 },
{ name: 'a班', count: 3, week: 3 },
{ name: 'b班', count: 4, week: 3 }
];
// 计算各班级打扫卫生的总数
const totalByClass = {};
list.forEach(item => {
const { name, count } = item;
if (!totalByClass[name]) {
totalByClass[name] = 0;
}
totalByClass[name] += count;
});
console.log('各班级打扫卫生的总数:', totalByClass);
// 计算平均每周打扫次数
const totalByWeek = {};
const countByWeek = {};
list.forEach(item => {
const { week, count } = item;
if (!totalByWeek[week]) {
totalByWeek[week] = 0;
countByWeek[week] = 0;
}
totalByWeek[week] += count;
countByWeek[week]++;
});
const averageByWeek = {};
for (const week in totalByWeek) {
averageByWeek[week] = totalByWeek[week] / countByWeek[week];
}
console.log('平均每周打扫次数:', averageByWeek);
```
运行上述代码,将得到以下输出:
```
各班级打扫卫生的总数: { a班: 6, b班: 8, c班: 5 }
平均每周打扫次数: { '1': 3.5, '2': 5, '3': 3.5 }
```
这里我们使用了两个对象 `totalByClass` 和 `totalByWeek` 来分别存储各班级的总数和每周的总数。然后,通过计算每周打扫次数的总和和出现的次数,我们得到了平均每周打扫次数的结果。
阅读全文