首页 > 解决方案 > 打字稿:数组的函数查找正在工作,但如果我检查它是否使用 if 语句返回一个值,它就不起作用

问题描述

我有这个代码:

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 并创建一个具有相同产品的新项目。

标签: javascriptarraystypescriptfind

解决方案


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

在 JavaScript 中检查对象的问题是:

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

这是正确的。一个对象不等于一个对象,除非它是完全相同的对象。查看您的代码,您的产品对象似乎应该是相同的,因为这些对象是通过引用传递的,但可能在 TypeScript 类构造函数的底层发生了一些事情,导致对象不一样。或者也许你的代码中的其他地方导致它们不存在。无论如何,最好只通过其唯一 ID 检查您的产品,如下所示(简化代码):

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,则绝对应该考虑添加一些。


推荐阅读