Problems generating JavaScript sums

1

I am making a script that allows me to perform operations to generate the total cost of the products:

  var subtotal = 0;
  var ivaValor = 0;
  var total = 0;
  selected.forEach(function(dato) {
      var pretotal = dato.price * dato.quantity;
      parseFloat(pretotal)
      var total = total + pretotal;

  });
  console.log(total);

But total returns it to me as Not a number (NaN), at the moment I do not understand what happens since total is declaring int.

Note: I'm starting in JS:)

    
asked by BorrachApps Mex 20.09.2017 в 21:08
source

1 answer

2

I could not make it show me NaN but I could notice that you are stating 2 variables total , one outside the foreach and another inside:

  //...
  var total = 0; // declaracion de variable total
  selected.forEach(function(dato) {
      var pretotal = dato.price * dato.quantity;
      parseFloat(pretotal)
      var total = total + pretotal; // otra vez declarando la variable total

  });
  console.log(total); // imprimes la variable total con el ambito global

Due to the last line I infer that you want to add the value of operations dato.price * dato.quantity; to variable total within foreach . Eliminate the declaration of the total internal variable of forEach for the operation to work:

var selected = [
 {
  price : 44,
  quantity: 2
 },
 {
  price : 20,
  quantity: 1
 }
];

var subtotal = 0;
var ivaValor = 0;
var total = 0;
selected.forEach(function(dato) {
    var pretotal = dato.price * dato.quantity;
    parseFloat(pretotal)
    total = total + pretotal;

});
console.log(total);
    
answered by 20.09.2017 / 23:20
source