[英]Adding Items to an Empty Array with Javascript
我只是在學習 Javascript,需要構建一個購物車。 我正在使用下拉菜單來選擇存儲在另一個數組中的項目。 然后我想將所選項目推送到一個名為“cart”的空數組
這是我用來從目錄數組中選擇數據以便將其推送到購物車數組的代碼:
let addFCat = document.getElementById('addfromCat');
function cat_Cart(){
// find out the index of the item loaded
let e = document.getElementById("productList");
let itemIndex = e.options[e.selectedIndex].value;
console.log(itemIndex);
// update item to cart
cart.push(catalog[itemIndex]);
localStorage.setItem("cart", JSON.stringify(cart));
// alert with updated total
// alert(`You added ${cartItems.name} to your Cart`)
}
但由於某種原因,我的購物車 [] 仍然是空的。
如果我在控制台中手動輸入: cart.push(catalog[ enter index here ]) ,然后: cart.length; 購物車更新。 我做錯了什么,它不會在函數中更新我的購物車?
(PS。我正在使用 console.logs 來檢查代碼是否正在運行)
我認為這是因為您確實刷新了瀏覽器,並且它導致您的購物車 [] 為空,我建議您先將購物車數組以空狀態存儲到 localStorage,然后像這樣獲取更新后的值
const cart = [] localStorage.setItem("cart", JSON.stringify(cart)); function cat_Cart(){ const getCart = JSON.parse(localStorage.getItem("cart")); // find out the index of the item loaded let e = document.getElementById("productList"); let itemIndex = e.options[e.selectedIndex].value; console.log(itemIndex); // update item to cart getCart.push(catalog[itemIndex]); localStorage.setItem("cart", JSON.stringify(getCart)); // alert with updated total // alert(`You added ${cartItems.name} to your Cart`) }
本地存儲將幫助您保存任何數據,即使您刷新瀏覽器也不會被刪除。 謝謝你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.