我正在学习 localStorage,我正在尝试构建一个基本的购物车功能。过程是:
但我不断收到 TypeError: UpdatedShoppingCartArray.push 不是函数 HTMLButtonElement.addToCart 第 5 步出错。
这是我的代码:
// simulate a product in the localStorage.
let prepTesting = {
name: "Tshirt: Enter the Red Dragon",
price: 3225,
qty: 1
};
localStorage.setItem("shoppingCart", JSON.stringify(prepTesting));
// Get values from product index.html page
let order_item_name = document.getElementById('order_item_name');
let order_item_price = document.getElementById('order_item_price');
let order_item_qty = document.getElementById('order_qty');
// initialize buttons
const btn_addToCart = document.getElementById('btn_addToCart');
const btn_clrLocalStorage = document.getElementById('btn_clrLocalStorage');
// set object with product order values
let itemToAdd = {
name: order_item_name.dataset.name,
price: parseInt(order_item_price.dataset.price),
qty: parseInt(order_item_qty.value)
};
function clrLS(e) {
e.preventDefault();
localStorage.clear();
location.reload();
}
function addToCart(e) {
e.preventDefault();
// assign localStorage("shoppingCart") to shoppingCart to check if it exists
let shoppingCart = localStorage.getItem("shoppingCart");
if (shoppingCart === null) {
// push itemToAdd to localStorage
localStorage.setItem("shoppingCart", JSON.stringify(itemToAdd));
}else {
// initialize array to insert localStorage array
let updatedShoppingCartArray = [];
// get and insert localStorage into updatedShoppingCartArray
updatedShoppingCartArray = JSON.parse(localStorage.getItem("shoppingCart"));
// clear localStorage for clean setting.
localStorage.clear();
// push itemToAdd into updatedShoppingCartArray
// This is where I get the "updatedShoppingCartArray.push is not a function" error
updatedShoppingCartArray.push(itemToAdd);
console.log(updatedShoppingCartArray);
// set updatedShoppingCart to localStorage
localStorage.setItem("shoppingCart", JSON.stringify(updatedShoppingCartArray));
}
}
btn_addToCart.addEventListener('click', addToCart);
btn_clrLocalStorage.addEventListener('click', clrLS);
我相信我的伪代码是正确的,但我无法弄清楚运行脚本时出现的错误是什么问题。
任何指导将不胜感激。谢谢你。
if (shoppingCart === null) {
// push itemToAdd to localStorage
localStorage.setItem("shoppingCart", JSON.stringify([itemToAdd]));
}
您需要将初始项目放入数组中。
目前,您将初始对象作为对象放入,而不是其中包含单个对象的数组。