javascript - 打字稿:数组的函数查找正在工作,但如果我检查它是否使用 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 并创建一个具有相同产品的新项目。
解决方案
我认为您想通过唯一标识符而不是产品本身来检查您的产品是否相等。
在 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,则绝对应该考虑添加一些。
推荐阅读
- javascript - React Datepicker onclick 在 Edge 和 IE 浏览器中不起作用
- mysql - SQL SELECT MATCH AGAINST:不符合我需要的方式
- uiviewcontroller - 根据一组条件呈现标签栏控制器
- flutter - 如何在 Flutter 中的图像上叠加图标?
- mapbox - 如何在 Mapbox 中通过 url 添加自定义标记?
- javascript - 在太鼓测试中获取当前选定元素的值很热?
- pygears - PyGears 如何制作与门
- django - Nginx 内部位置完全忽略 django 并允许免费访问
- python - Theano张量长度未知,但可以在pymc3层次模型中添加
- maven - 如何在 maven-resources-plugin 中生成 maven 属性并稍后使用它?