0

我正在尝试在购物车中保存一系列“项目”。但是当它继续其他部分时,会发生错误“未捕获的类型错误:无法读取 null 的属性'项目'”请帮助代码有什么问题

var existing_cart = localStorage.getItem("cart");
existing_cart = JSON.parse(existing_cart);
console.log(existing_cart);

if (existing_cart.items instanceof Array) {

  existing_cart.items.push({
    'article_number': article_no,
    'quantity': quantity,
    'item_name ': item_name
  });
  console.log(existing_cart);
  localStorage.setItem("cart", JSON.stringify(existing_cart));

} else {

  var products = [{
    'article_number': article_no,
    'quantity': quantity,
    'item_name ': item_name
  }];
  var cart = {
    'items': products
  }
  localStorage.setItem("cart", JSON.stringify(cart));
  toastr.success('Have fun storming the castle!', 'Miracle Max Says');
}
4

2 回答 2

0

第一次运行代码时,本地存储中不会有任何内容,existing_cart因此null. 你需要检查一下。

改变

if (existing_cart.items instanceof Array) {

到:

if (existing_cart) {
于 2018-10-24T20:12:41.250 回答
0
var existing_cart = localStorage.getItem("cart") || '{"items":[]}';

如果是第一次运行代码,localStorage 可能没有该元素,在这种情况下它会返回 null 或 undefined。在这种情况下,您可以将其默认为允许逻辑流动而不会遇到空指针异常的 JSON。

于 2018-10-24T20:15:48.173 回答