首页 > 解决方案 > 查找表中最大的数字

问题描述

我的 Wordpress 网页上有一张表格。我想在这张表中找到最高、最低和平均价格。问题是价格显示在<span>一个类中。(请参阅以下链接中的示例)

http://jsfiddle.net/c69uf1xt/

<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=&quot;woocommerce-Price-amount amount&quot;>
<span class=&quot;woocommerce-Price-currencySymbol&quot;>€&lt;/span>10.00</span>
</del> 
 <ins>
 <span class=&quot;woocommerce-Price-amount amount&quot;>
  <span class=&quot;woocommerce-Price-currencySymbol&quot;>€&lt;/span>7.00</span>
</ins>
 "> 
<span class="wpt_product_price">
<del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€&lt;/span>10.00</span>
</del> 
<ins>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">€&lt;/span>7.00</span>
</ins></span>
</td>
</tr>
<tr>

有什么方法可以用 Javascript 找到这些数字,还是要求太复杂?

期待你的回信。

标签: javascriptwordpresshtml-table

解决方案


首先,将所有价格放入浮点数数组中。这样您就可以更轻松地操作数据。

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

推荐阅读