thank you for your previous help, now the toal quantity works perfectly. i have tried to aplly the same principle with the total price but it displays "nan" (" price += parseInt(monPanier[i].price);"). before adding this line, the total price diplayed was only one copy per item even eg there was two black items, 3 red items and 4 yellow, it was considered as total price one black + one red + one yellow. Thank you for your help.
let asynCompteur = 0;
let quantity = 0;
let price = 0;
for (let i = 0; i < monPanier.length; i++) {
fetch('http://localhost:3000/api/products/' + monPanier[i].id)/*appel de l'api*/
.then((reponse) => reponse.json())
.then((data) => {
/*asynCompteur pour réguler l'itération*/
asynCompteur = asynCompteur + 1;
//J'ajoute le prix et la quantité
quantity += parseInt(monPanier[i].quantity); price += data.price;
console.log('prix', asynCompteur, price, quantity);
price += parseInt(monPanier[i].price);
console.log(typeof monPanier[i].quantity);
if (asynCompteur === monPanier.length) {
document.querySelector("#totalQuantity").innerText = quantity;
document.querySelector("#totalPrice").innerText = price;
}
parseInt(asynCompteur) + 1when you addquantity += parseInt(monPanier[i].quantity,10);monPanier[i].quantityis a string. What doesconsole.log(typeof monPanier[i].quantity)prints?monPanier[i].quantityis type string. Conversion to integer is necessary since Javascript string concatenation operator+is the same as, and takes precedence over, integer addition. As already mentionedparseIntis one solution. Another is the unary operatorquantity += +monPanier[i].quantity;