2016-04-23 7 views
0

Ich versuche, Karte zu verwenden und zusammen zu reduzieren, um eine Funktion zu erstellen, wo es durch Array von Objekt durchläuft und einige Mathe, aber ich habe NAN. Warum?Map und reduzieren zurückgekehrten NAN-Wert

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>

Antwort

0

Objekteigenschaft discount_pricediscounted_price nicht, da alle x.discounted_price sind undefiniert ist NaN Werte Array (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>


Oder Sie können vermeiden, dass die map() Methode

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>

Für das Problem mit Präzision beziehen: How to deal with floating point number precision in JavaScript?

Verwandte Themen