获取数组值并添加它们(如果它们是数字)

时间:2018-06-11 04:09:04

标签: javascript jquery html

我想知道如何从代码生成的数组中获取值,然后才能将它们添加到单个变量中:

      var selector = 'input[name^="Textbook"]';
        $(selector).on('click', function() {
          var checked = $(selector + ':checked').map(function() {
            return {
              'type': this.type,
              'value': this.value
            };
          }).get().filter(function(o) {
            return '-1' !== o.value; // skip if value = -1(No)
          });
          console.log('checked inputs', checked);
        });
      }

我已经检查了javascript中的函数,例如.reduce,根据developer.mozila.org“将其缩减为单个值”。虽然我的目标是只添加数值,但数组也包含非数字值。我怎么能做到这一点?谢谢!

编辑: 这是一个数组示例,上面的代码通过变量“checked”可以输出:

Output of script above

我的目标是添加所有“值”数据并忽略非数字数据。

EDIT2:这是HTML代码。不太确定我如何向你展示一个工作版本,因为它依赖于PHP,而像jsfiddle这样的网站也不支持它。

                  <label class="radio-inline">
                    <input form="ES4S" type="radio" name="Supplies1" value="'.$Result[$i]['ID'].'"> Yes
                    <input form="ES4S" type="hidden" style="display:none" value="'.$Result[$i]['ID'].'" name="SuppliesID'.$i.'">
                  </label>
                  <label class="radio-inline">
                    <input form="ES4S" type="radio" name="Supplies1" value="-1">No
                  </label>

3 个答案:

答案 0 :(得分:2)

使用reduce并在将其计入总和时检查该值是否为数字:

var selector = 'input[name^="Textbook"]';

$(selector).parent().on('click', selector, function() {
  var checked = $(`${selector}:checked`).get()
  
  var sum = checked.reduce((c,p)=>{
    if (!(isNaN(+p.value)))
      c += +p.value;
    return c;
  },0)
  
  console.clear();
  console.log('sum',sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook" value="MPM Charge"> Yes
  <input form="ES4S" type="hidden" style="display:none" value="MPM Charge" name="Textbook">
</label>
<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook" value="100">No
</label>

<br>

<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook2" value="MPM Charge"> Yes
  <input form="ES4S" type="hidden" style="display:none" value="MPM Charge" name="Textbook2">
</label>
<label class="radio-inline">
  <input form="ES4S" type="radio" name="Textbook2" value="300">No
</label>

首先不需要进行过滤,因为这需要对数组进行两次迭代。使用reduce可以一次性完成所有操作。一元运算符(+)用于将弦数字转换为数字,以确保isNaN测试为正。

答案 1 :(得分:1)

您需要按数字过滤,然后使用减少来获取列表的总和

var priceList = [{value:"190"}, {value:"180"}, {value:"Charge"}];

//shorthand code

console.log(priceList.map(n => Number(n.value)).filter(n => !isNaN(n)).reduce(function(a, b) { return a + b; }));

//full code

priceList =priceList.map(n => Number(n.value));
priceList = priceList.filter(n => !isNaN(n));
let priceSum = priceList.reduce(function(acc, val) { return acc + val; });
console.log(priceSum);

答案 2 :(得分:0)

const checked = [{"type":"radio","value":"100"},{"type":"checkbox","value":"MPM Charge"},{"type":"radio","value":"100.25"},{"type":"radio","value":"100"},{"type":"radio","value":"MPM Charge"},{"type":"radio","value":"100.5"},{"type":"radio","value":"100"},{"type":"radio","value":"MPM Charge"}]

Array.prototype.sum_values = function (prop, i, running_total = 0) {

  const array = Object.assign([], this)

  if (i === 0) {
    return running_total
  } else {
    const val = array[i - 1][prop] // property you want to add up
    const num = Number(val) // convert string to number
    if (isNaN(num)) { // if converted string in not a number
      return array.sum_values(prop, i - 1, running_total) // add nothing
    } else {
      return array.sum_values(prop, i - 1, running_total + num) // add number
    }

  }

}

const test = checked.sum_values('value', checked.length)
console.log(test) // 500.75
// Place the function where your checked array is console logged
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
  var checked = $(selector + ':checked').map(function() {
    return {
      'type': this.type,
      'value': this.value
    };
  }).get().filter(function(o) {
    return '-1' !== o.value; // skip if value = -1(No)
  });
  let sum = checked.sum_values('value', checked.length)
  console.log('checked inputs', sum);
  return sum
})