首页 > 解决方案 > 使用带有材料 UI 的反应钩子的表中列的平均总值

问题描述

我正在尝试在表格底部显示列的平均值。

像这样的行

const rows = [
  createData("Frozen yoghurt", 159, 6.0, 24, 4.0), 
  createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
  createData("Eclair", 262, 16.0, 24, 6.0),
  createData("Cupcake", 305, 3.7, 67, 4.3),
  createData("Gingerbread", 356, 16.0, 49, 3.9)
];

并通过行映射

<TableCell>
        {rows.map((row) => (
          <TableCell align="right">
            {row.calories} 
          </TableCell>
        ))}
      </TableCell>
      <TableCell>
        total array: {rows.length} <br />
      </TableCell>

沙盒上的完整代码

感谢任何帮助

标签: reactjsmaterial-uireact-hooks

解决方案


我想这应该对你有用......

var average_cal = 0; // Average Calories

var total_cal = 0; // Total Calories

forEach(var row in rows){
 total_cal = total_cal + row.calories ; // Finding the Total Calories
}

avrage_cal = total_cal / rows.length; // Calculating the average claories

<TableCell>{average_cal}</TableCell> // Display the result in the cell

注意:您可以在适当的位置添加代码。这只是为了说明如何计算一列的平均值。您可以对所有列执行相同的操作。


推荐阅读