首先你先要了解数组的 findIndexmapindexOfpush方法

代码思想:

  1. 先把缓存中的cart获取出来
  2. findIndex找cart里面的商品id是否等于当前商品详情的id,存在返回下标,不存在返回-1
  3. map映射出cart里面的价格是否等于当前商品详情的价格(cart里面的商品都会map出来,符合的当前下标位置是true)
  4. indexOf查找map的返回值(当然要while都循环出来),会得到当前为true的下标
  5. 然后push到一个数组中
  6. 然后开始判断了,首先if(index == -1)说明cart里面没用当前商品详情的商品id,那就先增一条
  7. 下面就是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);

基本逻辑是这样的,我是新手,有说错的地方请说出来,让我改,不要喷

相关文章:

  • 2021-06-19
  • 2021-12-10
  • 2021-10-19
  • 2020-11-09
  • 2022-01-06
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-22
  • 2021-06-10
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
相关资源
相似解决方案