gpt4 book ai didi

javascript - localstorage javascript 中的效果更改

转载 作者:行者123 更新时间:2023-12-02 22:02:41 27 4
gpt4 key购买 nike

这是当用户单击添加到购物车按钮时将产品添加到购物车的代码

 addToCart(){
var cart = []
var cartObj = {}

var cartItem = { 'item': this.product, 'price':this.product.price, 'qty': 0 }
cartObj[this.product.id] = cartItem

if(!localStorage.getItem('cart')){
localStorage.setItem('cart', JSON.stringify(cart))
}

cart = JSON.parse(localStorage.getItem('cart'));

if(cart.length > 0){
if(cart.hasOwnProperty(this.product.id)){
cartObj = cart[this.product.id]
}
}

cartObj[this.product.id]['qty']++
cartObj[this.product.id]['price'] = this.product.price * cartObj[this.product.id]['qty']
cart.push(cartObj);
localStorage.setItem('cart', JSON.stringify(cart));
console.log('added')
}
}

我想要这样的东西,假设用户在同一个产品上点击 3 次。

['product_id': { 'item': this.product, 'price':this.product.price, 'qty': 3 }] 

但是 javascript 正在这样做

[
'product_id': { 'item': this.product, 'price':this.product.price, 'qty': 1 },
'product_id': { 'item': this.product, 'price':this.product.price, 'qty': 1 },
'product_id': { 'item': this.product, 'price':this.product.price, 'qty': 1 }
]

请帮忙

最佳答案

试试这个,应该可以解决问题

addToCart(){
var cart = []
var cartObj = {}

var cartItem = { 'item': this.product, 'price':this.product.price, 'qty': 0 }
cartObj[this.product.id] = cartItem

if(!localStorage.getItem('cart')){
localStorage.setItem('cart', JSON.stringify(cart))
}

cart = JSON.parse(localStorage.getItem('cart'));

//---------> this check condition needs to be fixed
// if(cart.length > 0){
// if(cart.hasOwnProperty(this.product.id)){
// cartObj = cart[this.product.id]
// }
// }
let itemIndex = cart.findIndex((val)=>val.hasOwnProperty(this.product.id));
if(cart[itemIndex]) {
cartObj=cart[itemIndex];
} else {
cart.push(cartObj);
}

cartObj[this.product.id]['qty']++
cartObj[this.product.id]['price'] = this.product.price * cartObj[this.product.id]['qty']
// cart.push(cartObj);
localStorage.setItem('cart', JSON.stringify(cart));
console.log('added')
}

关于javascript - localstorage javascript 中的效果更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com