打字稿:函数 find for array 正在运行,但如果我检查它是否使用 if 语句返回值,则它不起作用

Typescript: Function find for array is working but if I check if it's returning a value with an if statement, it doesn't work

我有这个代码:

class Cart {

  private currentCart: item[];

  constructor(private pService: ProductService) {
    this.currentCart = [];
  }

  add(product) {
    if (this.currentCart.find((i) => i.product === product) != undefined) {
      this.currentCart[
        this.currentCart.findIndex((i) => i.product === product)
      ].increaseAmount();
    } else {
      this.currentCart.push(new item(product));
    }
  }
}

class Item {
  product: any;

  amount: number;

  constructor(product) {
    this.product = product;
    this.amount = 1;
  }
  
  increaseAmount() {
    this.amount++;
  }

  decreaseAmount() {
    this.amount--;
  }
}

我的问题是我第一次激活添加功能,它起作用了,它创建了一个新项目,第二次,如果我发送的产品与我之前发送的产品相同,它不应该是未定义的因为它确实存在,但它没有进入if语句,它直接进入else并创建一个具有相同产品的新项目。

我认为您想通过唯一标识符而不是产品本身来检查您的产品是否相同。

检查 JavaScript 中对象的问题是:

console.log({} === {}); // false

没错。一个对象不等于一个对象,除非它是完全相同的对象。查看您的代码,似乎您的产品对象 应该 相同,因为这些对象是通过引用传递的,但也许 TypeScript class 导致对象不相同的构造函数。或者您代码中的其他地方可能导致它们不存在。无论如何,最好只通过其唯一标识来检查您的产品,就像这样(简化代码):

add(product) {
  if(this.currentCart.find(item => item.product.id === product.id)) {
    this.currentCart[this.currentCart.findIndex(item => item.product.id === product.id)].increaseAmount();
  } else {
    this.currentCart.push(new item(product)) 
  }
}

如果您的产品没有唯一 ID,您绝对应该考虑添加一些。