【问题标题】:highest and lowest value in each (jquery) [duplicate]每个(jquery)中的最高和最低值[重复]
【发布时间】:2019-04-24 00:04:32
【问题描述】:

此代码返回:

0: 100,
1: 10,
2: 120,
3: 1

我需要捕捉最高值和最低值。有什么办法吗?我需要var min = 1var max = 120

var activeChoose = $('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]');
  activeChoose.each(function (index, value) {
    if (!$($('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]'))[index].attributes.style) {
      $(this).each(function (fakeIndex, value) {
        console.log(index + ': ' + parseInt(value.innerText));
      })
}});

【问题讨论】:

  • 你愿意在哪里使用最小最大值?
  • Math.max(1, 3, 2)Math.min(1, 3, 2)?
  • 我想将此数字保存在值中
  • 提供一个例子,虽然它可能有错误。
  • 关于如何在 StackOverflow 上找到最小值和最大值的答案有很多。没找到吗??

标签: javascript jquery


【解决方案1】:

您可以创建maxmin 变量并检查,如果当前值大于max,并将其分配给maxmin,如果当前值较小则min

var min = 1;
var max = 0;
var activeChoose = $('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]');
  activeChoose.each(function (index, value) {

  if (!$($('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]'))[index].attributes.style) {
   $(this).each(function (fakeIndex, value) {
   console.log(index + ': ' + parseInt(value.innerText));
   var v = parseInt(value.innerText);
   max = max > v ? max : v;
   min = min > v ? v : min;
})}});

【讨论】:

    【解决方案2】:

    一种从数组中获取最小值和最大值的简单方法,您可以根据需要使用它们的值。

    getMinMax = (arr) => {
      return { min: Math.min(...arr), max: Math.max(...arr) }
    }
    
    const { min, max } = getMinMax([10, 1, 100, 120])
    
    console.log(`min: ${min}, max: ${max}`)

    【讨论】:

      【解决方案3】:

      您可以使用此代码:

      var activeChoose = $('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]');
      
      var minVal = 0;
      var maxVal = 0;
      activeChoose.each(function (index, value) {
      
      if (!$($('.filter--active-container').find('span[data-filter-param*="sFilterProperties"]'))[index].attributes.style) {
          $(this).each(function (fakeIndex, value) {
              if(minVal > parseInt(value.innerText)){
                  minVal = parseInt(value.innerText);
              }
              if(maxVal < parseInt(value.innerText)){
                  maxVal = parseInt(value.innerText);
              }
              console.log(index + ': ' + parseInt(value.innerText));
          })
      }
      });
      

      【讨论】:

        猜你喜欢
        • 2021-11-12
        • 2013-01-24
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        • 2012-07-14
        • 2017-08-27
        相关资源
        最近更新 更多