<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行。
我想从第二行中找到第一列中所有数字的平均数,因为第一行中只有文本。
答案 0 :(得分:0)
使用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>