首先你先要了解数组的 findIndex、map、indexOf,push方法
代码思想:
- 先把缓存中的cart获取出来
- findIndex找cart里面的商品id是否等于当前商品详情的id,存在返回下标,不存在返回-1
- map映射出cart里面的价格是否等于当前商品详情的价格(cart里面的商品都会map出来,符合的当前下标位置是true)
- indexOf查找map的返回值(当然要while都循环出来),会得到当前为true的下标
- 然后push到一个数组中
- 然后开始判断了,首先if(index == -1)说明cart里面没用当前商品详情的商品id,那就先增一条
- 下面就是else了,说明有这个商品的id。就for循环出indexOf出来的下标长度,在循环里面if当前的商品详情的另一种规格(比如铅笔,有一盒卖,有一根卖,当选择后价格会变的),如果当前选择的跟cart的价格一样,那就num++(商品的数量+1),在for循环外面也就是for的同级判断indexOf没用找到的数组,当前数组就为空了if(isdArr.length == 0),说明当前的商品id有,但是选择的规格的价格不一样,就增加一条。
话不多说上代码图片‘
下面再呈现代码
// 1.获取缓存中的购物车 的数据
let cart = wx.getStorageSync(“cart”) || [];
// 2.判断 商品对象是否存在于购物车数组之中
let index = cart.findIndex(v => v.item_id === this.GoodsInfo.item_id);
// 判断购物车数组中,是否有相同的价格,符合返回true,不符合返回false,不懂先去看看map
let priceIndex = cart.map(v => v.item_price === this.data.pirce)
// 循环找map出来的结果,找ture,返回下标,然后存放在isdArr里
let isd = -1;
let isdArr = []
while ((isd = priceIndex.indexOf(true, isd + 1)) != -1) {
isdArr.push(isd)
}
// 判断有没有规格,有规格没选择,提示一下
if (this.data.goodsObj.item_fication_param[0] !== ‘’ && !this.data.bgActive) {
if (!this.data.bgActive) {
wx.showToast({
title: ‘请选择规格’,
icon: ‘success’,
mask: true
});
}
} else {
if (index === -1) {
// 3.不存在 第一次添加
this.GoodsInfo.item_price = this.data.pirce
this.GoodsInfo.num = 1;
this.GoodsInfo.checked = true;
cart.push(this.GoodsInfo)
} else {
// 存在的话,至少购物车有一个同商品id的商品
// console.log(isdArr.length)
for (var i = 0; i < isdArr.length; i++) {
let index = isdArr[i]
// 同商品id,价格也相等,就数量++
if (this.data.pirce == cart[index].item_price) {
// console.log(111)
cart[index].num++
}
}
// 有相同商品id,但是没用相同的价格,isdArr就没用true的下标,那就新增
if (isdArr.length == 0) {
this.GoodsInfo.item_price = this.data.pirce
this.GoodsInfo.num = 1;
this.GoodsInfo.checked = true;
cart.push(this.GoodsInfo)
}
}
// 5.把购物车重新添加会缓存中
wx.setStorageSync(“cart”, cart);
基本逻辑是这样的,我是新手,有说错的地方请说出来,让我改,不要喷