正在計算我的購物車的總數,我似乎遇到了一個數字問題。我不確定這個功能哪里出了問題。如果我在編碼時沒有正確計算總數,請忽略,但是使用 JSON 我傳遞的是數字而不是字串。
JSON
{
"id": "611afa8b9069c9126cff3357",
"discount": {
"title": "None",
"type": "None",
"percent": 0
},
"items": [
{
"sku": 1000,
"qty": 2,
"price": 10.99
},
{
"sku": 1001,
"qty": 2,
"price": 16.99
},
{
"sku": 1003,
"qty": 1,
"price": 15.99
}
]
}
const calculateTotal = (items, discount) => {
let total = 0;
let discountAmt = 0;
console.log(discount);
console.log(items);
console.log(items.length);
for (let i = 0; (j = items.length), i < j; i ) {
discountAmt = 0;
if (discount.type == "Item" && discount.itemNum == j.sku) {
discountAmt = j.price * (discount.percent / 100);
total = total - discountAmt;
} else {
total = total j.price * j.qty;
}
}
if (discount.type == "Order") {
discountAmt = 0;
discountAmt = total * (discount.percent / 100);
total = total - discountAmt;
}
console.log(total);
return total;
};
控制臺回傳
{ title: 'None', type: 'None', percent: 0 }
[
{ sku: 1000, qty: 2, price: 10.99 },
{ sku: 1001, qty: 2, price: 16.99 },
{ sku: 1003, qty: 1, price: 15.99 }
]
3
NaN
NaN
uj5u.com熱心網友回復:
如果您想遍歷您的專案,那么您的回圈就不正確。
你可以這樣做:
for (let i = 0; i < items.length; i ) { // i as index
let j = items[i]; // j will have the object based on the index
discountAmt = 0;
if (discount.type == "Item" && discount.itemNum == j.sku) {
discountAmt = j.price * (discount.percent / 100);
total = total - discountAmt;
} else {
total = total j.price * j.qty;
}
}
或者更簡單:
for (let j of items) {
discountAmt = 0;
if (discount.type == "Item" && discount.itemNum == j.sku) {
discountAmt = j.price * (discount.percent / 100);
total = total - discountAmt;
} else {
total = total j.price * j.qty;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/330751.html
