gpt4 book ai didi

javascript - 在本地存储中创建多项目 JSON 对象

转载 作者:行者123 更新时间:2023-11-28 18:35:03 25 4
gpt4 key购买 nike

我刚开始使用 JSON 和 localStorage。

我正在尝试创建一个小型客户端“篮子”,它将 productID 存储在我的 localStorage 中的标题 cart 下。

目前,我的 cart localStorage 项目已被新的 productID 覆盖,而不是将 productID 添加为新项目。当然,购物车对象应该能够接受多个商品。

这是我的代码笔:http://codepen.io/franhaselden/pen/regVgj

我的 addToCart 函数非常简单,但我不会添加正确的 JSON 结构。我对在添加多个项目但键相同 (productID) 的情况下 JSON 结构应该是什么感到困惑

function addToCart(productID) {
localStorage.setItem('cart', JSON.stringify(productID));
}

最佳答案

使用数组:

function addToCart(productID) {
// Get stored array, if it's not set, it should be set to an empty array
var basket = localStorage.getItem('cart');
basket = basket ? JSON.parse(basket) : [];

basket.push(productID);
localStorage.setItem('cart', JSON.stringify(basket));
}

关于javascript - 在本地存储中创建多项目 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37258207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com