【问题标题】:main.js:114 Uncaught TypeError: Cannot set property 'incart' of undefinedmain.js:114 未捕获类型错误:无法设置未定义的属性“incart”
【发布时间】:2020-04-27 15:26:00
【问题描述】:

我为我的购物车创建了一个数组,其中的产品带有标签、价格、incart、名称,我试图在下面的代码中更改它们。

      function setItems(product)
{
    let cartItems = localStorage.getItem('productsInCart');
    cartItems = JSON.parse(cartItems);
    console.log("My cartItems are", cartItems);

    if (cartItems != null)
    {
        if (cartItems[product.tag] == undefined)
        {
            cartItems = 
            {
                ...cartItems,
                [product.tag]: product 
            }
        }

        cartItems[product.tag].incart += 1;
    }
    else 
    {
        product.incart = 1;
        cartItems = 
        {
        [product.tag]: product
        }

    }

【问题讨论】:

标签: javascript arrays shopping-cart


【解决方案1】:

product.tag 可能未定义,请检查您调用 setItems() 的位置;

if (cartItems[product.tag] == undefined) {
    cartItems = {
        ...cartItems,
        [product.tag]: product
    }
}

改成这个以获得更好的代码

if (!cartItems[product.tag]) {
    cartItems[product.tag] = product;
}

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 2020-09-19
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 2017-03-30
  • 2011-03-11
相关资源
最近更新 更多