如何从 sessionStorage 中检索对象?

How to retrieve objects from sessionStorage?

我正在生成菜肴列表(它们是对象),当用户单击按钮时,InitializeFoodList() 应该将所选项目添加到 sessionStorage。然后在 RetrieveDataFromCart() 中,我想遍历 sessionStorage 并在控制台中显示所有这些项目。

问题是最终结果是项目 属性 为空,或者它只显示最后添加的项目而下一个为空。

有人知道实现此目的的更好方法吗?

var list = [{
    id: 1,
    name: "Spaghetti",
    price: 15,
    category: "main",
    pictureSrc: "images/food/spaghetti.jpg"
  },
  {
    id: 2,
    name: "Lasagne",
    price: 20,
    category: "main",
    pictureSrc: "images/food/Lasagne.jpg"
  },
  {
    id: 3,
    name: "Coca-cola",
    price: 5,
    category: "drinks",
    pictureSrc: "images/food/cola.jpg"
  },
  {
    id: 4,
    name: "Chicken",
    price: 12,
    category: "main",
    pictureSrc: "images/food/chicken.jpg"
  },
];

function InitializeFoodList() {

  var foodList = $('#foodList');

  for (let i = 0; i < list.length; i++) {
    const element = list[i];
    var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>';
    foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>");
    $('#add' + i).click(function() {
      sessionStorage.setItem("cart", JSON.stringify(element));
    });
  }
}

function RetrieveDataFromCart() {

  var elements = [];

  for (let i = 0; i < sessionStorage.length; i++) {
    var element = JSON.parse(sessionStorage.getItem(localStorage.key(i)));
    elements.push(element);
    console.log(element.name);
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button onclick="InitializeFoodList()">Click me</button>
  <button onclick="RetrieveDataFromCart()">Retrieve</button>
  <ul id="foodList" class="list-inline"></ul>
</div>

我只想将整个数组存储在一个键下

然后你可以add/remove或者在内存中修改数组中的对象,每次修改时存储修改后的数组

function getStoredCart(){
    // return stored array and if not existing return an empty array
    return JSON.parse(sessionStorage.getItem('cart') || '[]')
}

function saveCart(array){
   sessionStorage.setItem("cart", JSON.stringify(array)); 
}

// example deleting item
function deleteItem(item){
    var itemIndex = cartList.indexOf(item)
    cartArray.splice(itemIndex,1); // remove from stored array       
    saveCart(cartArray ); // save it back into storage
}

// example adding item
function addItem(itemObject){       
    cartArray .push(itemObject); // push new object to array       
    saveCart(cartArray ); // save it back into storage
}


// keep array reference in variable whole time page is active
var cartArray = getStoredCart();

$.each(cartArray , function(i, item){
    // add the html for each item and use `item` reference in click handlers when doing modifications
})

您正确使用了 sessionStorage,但此代码段中存在一些问题。首先,在 sessionStorage 中设置项目时,每次都添加 'cart' 作为键,因此它会覆盖先前存储的值,因为 sessionStorage 中的项目存储为键值对,键应该是唯一的,否则它会更新先前存储的值在同一个键。

所以我用键名 'cart' 添加了 i 的值,即 'cart' + i 。您可以根据您的用例使用任何唯一键。 其次,不是使用 localStorage 获取特定密钥,而是使用会话存储(似乎是一些错字)

更新了代码段

var list = [{
    id: 1,
    name: "Spaghetti",
    price: 15,
    category: "main",
    pictureSrc: "images/food/spaghetti.jpg"
},
{
    id: 2,
    name: "Lasagne",
    price: 20,
    category: "main",
    pictureSrc: "images/food/Lasagne.jpg"
},
{
    id: 3,
    name: "Coca-cola",
    price: 5,
    category: "drinks",
    pictureSrc: "images/food/cola.jpg"
},
{
    id: 4,
    name: "Chicken",
    price: 12,
    category: "main",
    pictureSrc: "images/food/chicken.jpg"
},
];

function InitializeFoodList() {

var foodList = $('#foodList');

for (let i = 0; i < list.length; i++) {
    const element = list[i];
    var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>';
    foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>");
    $('#add' + i).click(function() {
    sessionStorage.setItem("cart" + i, JSON.stringify(element));
    });
}
}

function RetrieveDataFromCart() {

var elements = [];

for (let i = 0; i < sessionStorage.length; i++) {
    var element = JSON.parse(sessionStorage.getItem(sessionStorage.key(i)));
    elements.push(element);
    console.log(element.name);
}

}