[英]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.