javascript - 2行第一列的Javascript平均值
问题描述
<table>
<tr>
<th>Numbers</th>
<th>Names</th>
</tr>
<tr>
<th>2</th>
<th>Name 1</th>
</tr>
<tr>
<th>26</th>
<th>Name 2</th>
</tr>
</table>
在我的代码中,这些行是从数据库中导入的,因此它们都来自表中的第 2 行。
我想从第二行中找到第一列中所有数字的平均数,因为第一行中只有文本。
解决方案
使用Object#values、Array#reduce和querySelectorAll
const dataElements = document.querySelectorAll("table tr:not(:first-child) > th:first-child");
const res = Object.values(dataElements)
.reduce((a,c)=>a+Number(c.innerText),0)/dataElements.length;
console.log(res);
<table> <tr> <th>Numbers</th> <th>Names</th> </tr><tr> <th>2</th> <th>Name 1</th> </tr><tr> <th>26</th> <th>Name 2</th> </tr></table>
推荐阅读
- python - 如何让机器人在每个命令中给出不同的值
- python - 访问 JSON 对象中的元素
- php - 有没有办法减少循环次数
- php - set_exception_handler 未捕获类异常
- node.js - 在 node_modules/pino/pino.js:9 const { assertDefaultLevelFound, mappings, genLsCache } = require('./lib/levels') 中出现错误
- php - 使用 New Relic Infrastructure 代理的多行应用程序日志解析器
- python - Pandas Dataframe 3D 曲面图
- sql - 我在写游标时收到错误 ORA-01001 无效游标显示偶数条记录
- javascript - 如何在JSX中仅链接一个.map数组的一个元素
- c# - 服务文件供下载。浏览器忽略文件名并使用“file.nothing”代替