Web刷题记录——购物车

一、代码及解题思路

1、添加方法

(1)逻辑

a、需要判断本次添加的商品是否存在于购物车中【根据id值是否相等判断】

b、如果不存在,即设置num=1,并追加本次商品

c、如果存在,即只需设置数值+1

    【注意】 :这里需要变动的数据是购物车,因为页面根据该数据渲染

(2) 代码

addToCart(goods) 
// TODO:修改当前函数,实现购物车加入商品需求
// console.log(goods.id);
// 1、从【cartList】中浅拷贝出已经存在的商品数组
let res = this.cartList.filter((item) => {
    return item.id == goods.id
})

// 2、如果数组长度不为零即商品存在
// 那么我就更改【浅拷贝数组的num】这样【原数组cartList】也就随之改变
   if (res.length) {
     res[0].num += 1
   } else {
     goods.num = 1;
     this.cartList.push(goods);
   }
this.cartList = JSON.parse(JSON.stringify(this.cartList));
},

2、删除方法

(1)逻辑

a、因为要删除元素,所以要拿到元素索引【findIndex】

b、判断当前num是否>1,是则继续减,否则删除整个元素

(2)代码

removeGoods(goods) {
                // TODO:补全代码实现需求

                // 1、拿到添加商品的索引
                let index = this.cartList.findIndex((item) => {
                    return item.id == goods.id
                })
                console.log(index);

                // 2、索引存在
                if (index !== -1) {
                    // 2.1 不小于1 继续减
                    if (this.cartList[index].num > 1) {
                        this.cartList[index].num -= 1
                    } else {
                        // 2.2 小于1 调用删除方法【splice】
                        this.cartList.splice(index, 1)
                    }

                }
            }
        }

二、涉及到的知识

1、filter【浅拷贝】

【理解】浅拷贝出满足条件的数组,因此在改变该数组时,原数组也会改变

(1)语法

filter(callbackFn)
filter(callbackFn, thisArg)

 (2)例子

const fruits = ["apple", "banana", "grapes", "mango", "orange"];

/**
 * 根据搜索条件(查询)筛选数组项
 */
function filterItems(arr, query) {
  return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}

console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']

2、findIndex【找索引】

返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1

(1)语法

findIndex(callbackFn)
findIndex(callbackFn, thisArg)

 (2)例子

console.log([1, , 3].findIndex((x) => x === undefined)); // 1

3、splice【删除】

【MDN】splice() 方法就地移除或者替换已存在的元素和/或添加新的元素。

要创建一个删除和/或替换部分内容而不改变原数组的新数组,请使用 toSpliced()

(1)语法

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)

(2)例子

const myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"];
const removed = myFish.splice(2, 2);

// myFish 是 ["parrot", "anemone", "sturgeon"]
// removed 是 ["blue", "trumpet"]

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值