首页 > 解决方案 > 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 行。

我想从第二行中找到第一列中所有数字的平均数,因为第一行中只有文本。

标签: javascripthtmlhtml-tableaverage

解决方案


使用Object#valuesArray#reducequerySelectorAll

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>


推荐阅读