2016-04-23 82 views
0

我尝试使用map和reduce一起构建一个函数,它通过对象数组循环并做一些数学运算,但是我得到了NAN。为什么?映射并减少返回的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>

回答

0

对象属性是不discount_pricediscounted_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?