【问题标题】:Cannot read property 'slice' of undefined on class Cart无法读取类 Cart 上未定义的属性“切片”
【发布时间】:2020-06-27 07:57:08
【问题描述】:

我对 cart 的某个类有疑问,我必须在工作中使用它。 这是这个类的代码:

class Cart {
  constructor() {
    this.key = "IT_SPA_CART";

    if (!this.exists()) {
      this.setItSpaCart([]);
    }
  }

  get() {
    const cookies = document.cookie.split(";");
    return cookies.find(cookie => cookie.startsWith(this.key));
  }

  exists() {
    return this.get() !== undefined;
  }

  getItSpaCart() {
    const cookieValue = this.get().slice(12);
    const parsedValue = JSON.parse(cookieValue);

    return parsedValue;
  }

  setItSpaCart(value) {
    const stringifiedValue = JSON.stringify(value);
    document.cookie = `${this.key}=${stringifiedValue}`;
  }

  add(item) {
    const cartValue = this.getItSpaCart();
    this.setItSpaCart([...cartValue, item]);
  }

  remove(item) {
    const cartValue = this.getItSpaCart();
    const itemInCart = cartValue.findIndex(val => val.name === item.name);

    if (itemInCart !== -1) {
      cartValue.splice(itemInCart, 1);
      this.setItSpaCart(cartValue);
    }
  }
}

当我尝试使用这个类时,例如使用 add() 方法,如下所示:

let cart = new Cart();
cart.add([{ num: 1, cost: 2 }, { num: 3, cost: 4 }, { num: 5, cost: 6 }]);

出现此错误:

无法读取 Cart.getItSpaCart 中未定义的属性“切片”

为什么会这样?

感谢您的每一个提示。

【问题讨论】:

  • cart.get 返回undefined,也许cookie.startsWith(this.key) 没有找到..?
  • 当我运行'console.log(cart);'然后在控制台上,我有:'Cart {key:“IT_SPA_CART”}',但在 Cookies 控制台上的“应用程序”部分中没有任何内容......
  • 是的,对象中的key属性存在,但是cookie找不到,不存在,或者是HTTPOnly(在DevTools中应该还是可以看到的),可以不会被 JS 读取。但我们无法回答为什么 cookie 不存在...
  • 我更改了这一行:return cookies.find(cookie => cookie.startsWith("IT_SPA_CART"));
  • 现在正在工作 - 奇怪...

标签: javascript typeerror slice


【解决方案1】:

我遇到了同样的问题 ;-) 也许您已经知道如何解决它,但如果不知道,也许解决方案是更改此行中的代码:const cookies = document.cookie.split(";");。我把 ("; ) 改成了 ("; ")。

【讨论】:

  • 嗨,谢谢你的提示,但在我的代码中,我有这样的代码:const cookies = document.cookie.split(";"); 在我的情况下,问题是当密钥不是第一个在 cookie 文件中时更改密钥的名称。在设置键名空白之前。
猜你喜欢
  • 1970-01-01
  • 2019-12-26
  • 2021-09-26
  • 1970-01-01
  • 2016-02-08
  • 2019-06-14
  • 1970-01-01
  • 2018-07-18
  • 2016-05-07
相关资源
最近更新 更多