javascript div 长度如果值大于

javascript div length if value greater than

我需要你的帮助,了解如何获得 div class 的长度,例如值 >= 20

<td class="total">23</td>
<td class="total">12</td>
<td class="total">3</td>
<td class="total">42</td>

在我的示例中,我总共有 4 条记录 class。但结果应该是 2 因为只有 2 条记录 >= 20

这是我的尝试:

   $(".total").each(function() {
      var val = $.trim( $(this).text() );
      if ( val >= 20) {
          val = parseFloat( val.replace( /^$/, "" ) );
          length = $(".total").length // but this will show me all records which is not correct
          sum += !isNaN( val ) ? val : 0;
      }
    });
    console.log( sum );
    console.log( length );

如果您的标准匹配,您应该增加长度值

var length = 0;
 $(".total").each(function() {
      var val = $.trim( $(this).text() );
      if ( val >= 20) {
          val = parseFloat( val.replace( /^$/, "" ) );
          length++;
          sum += !isNaN( val ) ? val : 0;
      }
    });
    console.log( sum );
    console.log( length );

您可以过滤其 innerText 大于 20 的单元格

console.log(
  $('.total').filter((index,td)=>parseInt(td.innerText, 10)>=20).get()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tr>
<td class="total">23</td>
<td class="total">12</td>
<td class="total">3</td>
<td class="total">42</td>
</tr>
</table>

您可以使用 reduce to 创建一个包含 sumlength 值的对象:

let result = [...document.querySelectorAll('.total')].reduce((obj, itm) => {
  let val = parseFloat(itm.textContent)
  if(val >= 20) {
    obj.sum += val
    obj.length++
    obj.items.push(itm)
  }
  return obj
}, {sum: 0, length: 0, items: []})

console.log(result)
<table>
  <tr>
    <td class="total">23</td>
    <td class="total">12</td>
    <td class="total">3</td>
    <td class="total">42</td>
  </tr>
</table>