映射并减少返回的NAN值

时间:2016-04-23 04:38:38

标签: javascript jquery

我尝试使用map并一起缩小来构建一个函数,它通过对象数组循环并做一些数学但是我得到了NAN。为什么呢?

function getTotal(){
 var obj = [
  {
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  },
  {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }
];
  
          return obj.map(function(x){;return x.discounted_price * x.qty}).reduce(function(a,b){return a + b});

 
 }

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>

1 个答案:

答案 0 :(得分:0)

对象属性为discount_price而非discounted_price,因为x.discounted_price未定义,所有数组值均为NaNWhen and why number evaluates to NaN, after multiplying, in Javascript?)。

function getTotal() {
  var obj = [{
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  }, {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }];

  return obj.map(function(x) {;
    return x.discount_price * x.qty
    // -------------^------ bug is here
  }).reduce(function(a, b) {
    return a + b
  });


}

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>

或者您可以避免使用map()方法

function getTotal() {
  var obj = [{
    "name": "item 1",
    "discount_price": 86.9,
    "qty": 1,
  }, {
    "name": "item 2",
    "discount_price": 11.9,
    "qty": 1,
  }];

  return obj.reduce(function(a, b) {
    return a.discount_price * a.qty + b.discount_price * b.qty
  });

}

$('p').text(getTotal());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<p></p>

对于精度问题,请参考:How to deal with floating point number precision in JavaScript?