【问题标题】:Map and reduce returned NAN value映射和减少返回的 NAN 值
【发布时间】:2016-04-23 04:38:38
【问题描述】:

我尝试同时使用 map 和 reduce 来构建一个函数,在该函数中循环遍历对象数组并进行一些数学运算,但我得到了 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>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    对象属性是discount_price 不是discounted_price,因为x.discounted_price 未定义所有数组值都是NaN (When 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?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2023-04-03
      • 2021-09-13
      相关资源
      最近更新 更多