問題在於subtractQuantity函數。例如,當我添加兩個產品時,我點擊了第一個產品的減去數量按鈕,第二個產品也減去了它的數量。它應該是第一個減去數量的產品,因爲我點擊了第一個產品的減數按鈕。第二個問題是當數量爲0時,它應該自動刪除產品,但錯誤說明array.splice不是函數。 PS:我使用的EcmaScript 6,請自由地指導我如果我不使用ECMAScript 6或什麼來改善我的代碼減去幾個產品數量和Array.Splice不是函數
const cart = {};
function AddtoCart(productid, description, quantity, price) {
if (cart[productid]) {
cart[productid].qty += quantity;
} else {
cart[productid] = {
id: productid,
desc: description,
qty: quantity,
price: price
};
}
calculateGrandTotal();
document.getElementById("total").innerHTML = GrandTotal;
console.log(GrandTotal);
viewCart();
}
function subtractQuantity(productid){
if(cart[productid].qty > 0){
cart[productid].qty--;
}
if (cart[productid].qty == 0) {
delete cart[productid]//Remove from cartreturn false;
}
viewCart();
}
function calculateGrandTotal(){
GrandTotal = 0;
for(let productid in cart){
if(cart.hasOwnProperty(productid)){
GrandTotal += parseFloat(cart[productid].price) * parseInt(cart[productid].qty);
}
}
}
function viewCart() {
let tbody = document.getElementById('cartsBody');
tbody.innerHTML = '';
Object.values(cart).forEach(content => {
tbody.innerHTML += `<td>${ content.id }</td>
<td>${ content.desc }</td>
<td>${ content.qty }</td>
<td>${ content.price }</td>
<td>${ content.qty * content.price }</td>
<td><button type='submit' onClick='subtractQuantity(${content.id})'>subtract Quantity</button></td>`;
});
}
<script src="script.js"></script>
<input type="button" value="Laptop" onclick="AddtoCart('132','Macbook Pro', 1, 79000,0)" />
<input type="button" value="Phone" onclick="AddtoCart('456','Iphone 5S', 1, 18000,0)" />
<input type="button" value="Camera" onclick="AddtoCart('789','Nikon 3D00', 1, 25000,0)" />
<table border="1" id="cartsTable">
<thead>
<tr>
<th>Product ID</th>
<th>Product Description</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="cartsBody">
</tbody>
</table>
<h4>Total:</h4>
<p id="total"></p>
我想是因爲車是一個對象,拼接是數組 –
@AshtonMorgan。是的,這是問題所在。你可以幫我嗎? – Joseph
阿什頓說的是正確的。你不能拼接對象屬性。改爲使用delete或爲購物車創建數組。 – Janne