im trying to get the total price for a array of products but when i try it, it just return NaN im kinda new to JavaScript so i might be doing it wrong
so i have a multidimensional array where i keed the data from the products then whit that data i create a table to display the data in the navigator but when i try to add all the price data to total it just say NaN in Navigator but i dont understand why because im using parseInt() method any idea why this could be happening? im running out of ideas to solve this.
JavaScript:
let carrito = [];
let continuar;
let figura;
let precio;
let cantidad;
let total;
do{
figura = prompt("Figura de acción:");
precio = prompt("Precio:");
cantidad = prompt("Cantidad:");
carrito.push([figura, cantidad, precio]);
continuar = prompt("¿Continuar?");
}while(continuar != "n");
console.log(carrito)
crearTabla()
function crearTabla(){
let tabla = "<thead><tr><th>Producto</th><th>Cantidad</th><th>Precio</th></tr></thead>"
for (var i = 0; i < carrito.length; i ) {
tabla = `<tr><td>${carrito[i][0]}</td><td>${carrito[i][1]}</td><td>${carrito[i][2]}</td></tr>`
total = parseInt(carrito[i][2]);
console.log(carrito[i][2]);
}
tabla = `<tr><td>---</td><td>Subtotal:</td><td>${total}</td></tr>`
document.getElementById("factura").innerHTML = tabla;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculadora</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="js/app.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-7 zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG 2QOK9T ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</head>
<body>
<div>
<table id="factura"></table>
<button type="button" onclick="calcular()">Calcular</button>
</div>
</body>
</html>
CodePudding user response:
Initialize total as total = 0; - if you type undefined 1 into the console of the browser dev tools it returns NaN. Without initializing total that is the result.
console.log(undefined 1);
let total;
console.log('Total: ', total = 1);
let goodTotal = 0;
console.log('Good total: ', goodTotal = 1);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
