购物车.js
var Cart = function Cart(oldCart) {
this.items = oldCart.items || [];
this.add = function (item) {
this.items.push(item);
}
}
我的 index.js 路线
router.post('/cart', (function (req, res) {
var productid = req.body.id
var myCart = new Cart(req.session.cart ? req.session.cart :{})
//query the db and return the correct object
Products.findById({ _id: productid }, function (err, product) {
//if there is an error...
if (err) {
return res.redirect('/');
}
myCart.add(product);
req.session.cart = myCart;
console.log(req.session.cart);
res.redirect('/');
});
}));
在代码示例的末尾,您包含了这段代码,我认为它是 cart.js 的代码
function Cart(oldCart = {}) {
this.items = oldCart.items || [];
this.add = function (item) {
this.items.push(item)
}
}
但它以 (oldCart= {}) 作为参数给我错误。所以我删除了它。 现在,每当我按下一个项目时,我都会将一个项目添加到购物车中。它不包括之前点击过的项目。
这是console.log,注意'草莓'在我的第一个请求中,然后我被重定向到索引页面并点击'Apple',假设在第二个请求中累积产品以显示购物车:['草莓', '苹果']
当我在将 product2 和 product2 添加到购物车的地方运行您的代码时,这就是它正确显示购物车的方式,因为它在购物车中显示了两个项目,这是正常行为。
非常感谢您的宝贵时间,并为占用您的时间表示歉意
我是否需要使用 for 循环遍历 myCart 对象以显示其中的所有项目而不是我最后添加的项目?
最佳答案
既然你向我解释了你想要完成的事情,我会帮助你以最简单的方式完成。
我们将从重新格式化您的代码开始。您的 items
属性当前是一个对象 {}
,但我们将改用数组 []
。
`this.items = oldCart.items || []`
由于 items
现在是一个数组,我们将使用您创建的 add
方法将新项目push
到其中。我将其修改为:
this.add = function(item){
this.items.push(item);
}
这就是您所需要的。现在在您的代码中,在您为数据库获取产品后,将其添加到 cart.items
,然后将其传递给您的 session :
Products.findById({ _id: productid }, function (err, product) {
if (err) {
return res.redirect('/');
}
//add the product to cart.items
cart.add(product)
//pass cart.items to the session
req.session.cart = cart.items;
req.session.save(function (err) {
return
});
//instantiate new cart object
const myCart = new Cart;
const product1 = {id:1, name:'orange', price:1};
const product2 = {id:2, name:'apple', price:2};
//add products
myCart.add(product1);
myCart.add(product2);
//you can see the added products
console.log(myCart.items)
function Cart(oldCart = {}) {
this.items = oldCart.items || [];
this.add = function (item) {
this.items.push(item)
}
}
关于Javascript 函数不执行且不返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577672/