javascript - 查找表中最大的数字
问题描述
我的 Wordpress 网页上有一张表格。我想在这张表中找到最高、最低和平均价格。问题是价格显示在<span>
一个类中。(请参阅以下链接中的示例)
<tr>
<td>Product 1</td>
<td>01-12-2018</td>
<td class="wpt_price" id="price_value_id_1306" data-price_html="
<del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€</span>10.00</span>
</del>
<ins>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€</span>7.00</span>
</ins>
">
<span class="wpt_product_price">
<del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€</span>10.00</span>
</del>
<ins>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€</span>7.00</span>
</ins></span>
</td>
</tr>
<tr>
有什么方法可以用 Javascript 找到这些数字,还是要求太复杂?
期待你的回信。
解决方案
首先,将所有价格放入浮点数数组中。这样您就可以更轻松地操作数据。
var pricesarray = document.getElementsByTagName("ins");
var prices = [];
for(index = 0;index<pricesarray.length;++index){
prices.push(parseFloat(pricesarray[index].innerText.replace("€","")));
}
然后得到最高和最低的数字
var highest = Math.max.apply(Math,prices );
var lowest = Math.min.apply(Math,prices );
对于平均值,我们需要减少并编写一个函数将数组减少为和,然后将其除以数组的长度
var sum = prices.reduce(add, 0);
function add(a, b) {
return a + b;
}
var average = sum/prices.length;
我们终于得到它了。
> lowest
4
> highest
11
> average
7.333333333333333
推荐阅读
- python - 在一个范围内只使用一次函数的问题
- c# - 如何使用正则表达式从以下模式中提取数字: {"idProveedors":["73","3","67333"]} in C#
- json - 无法在 post 请求中发送阿拉伯文本
- javascript - 对象数组转换以获取对象数组中每个属性的计数
- django - 在 Elastic Beanstalk Aws React Django 上托管站点时如何从单独的 S3 存储桶加载静态文件
- intellij-idea - 在插件测试中修改 IntelliJ 自定义属性
- logging - how to log to a file with Deno
- javascript - 使用一个标题行数组和表的其余标题值数组操作 JSON 键值
- r - 有效地将日期列的小时更改为另一个数据框列 R 的值
- python - 在 python 中,如何用其组成数据填充条形图中的每个条形?