我正在尝试使用sessionStorage构建购物车的开头,并且发现了一些奇怪的行为。
我希望能够将多个对象添加到sessionStorage中,因此我正在使用一个数组,该数组使用JSON.parse()和JSON.stringify()从存储中添加/提取数据。
第一次添加产品时,它会看到没有存储空间,我们初始化一个数组,然后将模拟产品推入该数组。然后,我们对数组进行JSON.stringify()并将其添加到存储中。
下次添加产品时,检查将发现sessionStorage中已经有东西。这是奇怪的行为...第二个产品尚未推送到阵列,但是当您注销sessionStorage的内容时,它已经显示了2个项目。此外,当我在if()语句之后但在将产品推入数组之前注销sessionStorage的内容时,它再次仅显示数组中的一项。
$("#addToCart").click(function() {
//see what is in storage before running function
var SessionContents =
JSON.parse(sessionStorage.getItem("products"));
console.log("Initial session contents ", SessionContents);
//create product object
var prodToAdd = {
"prodName": "name",
"prodSize": "size",
"prodColor": "color",
"prodID": "id",
"prodNum": "num"
};
//some products already in storage
if (sessionStorage.products) {
var products = JSON.parse(sessionStorage.getItem("products"));
//***After the first initial product add, after each addition click, this always shows the product added to the sessionStorage even though it hasn't been added yet! It gets added on line 31. Additionally, why does this log out showing 1 more item in the sessionStorage than what we see in the log on line 29?***
console.log("prods in storage: ", products);
} else {
//no products in storage, initialze array
console.log("no products exist");
var products = [];
}
var SessionContents = JSON.parse(sessionStorage.getItem("products"));
console.log("Products b4 push ", SessionContents);
products.push(prodToAdd);
sessionStorage.setItem("products", JSON.stringify(products));
//new product has been added, check status of sessionStorage
var SessionContents = JSON.parse(sessionStorage.getItem("products"));
console.log("final products ", SessionContents);
});
$('#clearSesh').click(function() {
sessionStorage.clear();
});
<button id='addToCart' type="button">add product</button>
<button id='clearSesh' type="button">Clear Session</button>
感谢您的帮助!