gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property 'push' of null

转载 作者:行者123 更新时间:2023-11-30 20:41:26 24 4
gpt4 key购买 nike

我已经离线测试了我的代码,现在我把它放在一个域上并托管,购物车系统不工作并出现错误

   cart.js:22 Uncaught TypeError: Cannot read property 'push' of null
at Object.shoppingCart.addItemToCart (cart.js:22)
at HTMLAnchorElement.<anonymous> (index2b.html:469)
at HTMLAnchorElement.dispatch (jquery-3.3.1.min.js:2)
at HTMLAnchorElement.y.handle (jquery-3.3.1.min.js:2)

我试过 if cart == null then cart = [] 但它不起作用。我的页面是一个食品/外卖菜单,当您单击食品时,价格会添加到购物车,但它会被完全禁用。

这是我的 JS

    //*******************************************************//
//** shopping cart fucntions

var shoppingCart = {};
shoppingCart.cart = [];
shoppingCart.Item = function(name, price, count) {
this.name = name
this.price = price
this.count = count
};


shoppingCart.addItemToCart = function(name, price, count) {
for (var i in this.cart) {
if (this.cart[i].name === name) {
this.cart[i].count += count;
this.saveCart();
return;
}
}
var item = new this.Item(name, price, count);
this.cart.push(item);
this.saveCart();
};


shoppingCart.removeItemFromCart = function(name) { // removes one item
for (var i in this.cart) {
if (this.cart[i].name === name) {
this.cart[i].count --;
if (this.cart[i].count === 0) {
this.cart.splice(i, 1);
}
break;
}
}
this.saveCart();

};


shoppingCart.removeItemFromCartAll = function(name) {// removes all item name
for (var i in this.cart) {
if (this.cart[i].name === name){
this.cart.splice(i,1);
break;
}
}
this.saveCart();
};


shoppingCart.clearCart = function() {
this.cart = [];
this.saveCart();
};


shoppingCart.countCart = function() { // -> return total couNt
var totalCount = 0;
for (var i in this.cart) {
totalCount += this.cart[i].count;
}

return totalCount;
};

shoppingCart.totalCart = function() { // -> return total coSt
var totalCost = 0;
for (var i in this.cart){
totalCost += this.cart[i].price * this.cart[i].count;
}
return totalCost.toFixed(2);
};


shoppingCart.listCart = function() { // -> array of item
var cartCopy = [];
for (var i in this.cart) {
var item = this.cart[i];
var itemCopy = {};
for (var p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = (item.price * item.count).toFixed(2);
cartCopy.push(itemCopy);
}
return cartCopy;
};

shoppingCart.saveCart = function() {
localStorage.setItem("shoppingCart", JSON.stringify(this.cart));
};

shoppingCart.loadCart = function() {
this.cart = JSON.parse(localStorage.getItem("shoppingCart"));
};


shoppingCart.loadCart();

请帮忙,这是该项目的最后阶段。提前谢谢你。

最佳答案

插入此代码 cart = cart || []; 在脚本的第 21 行。希望这对以后的人有帮助。

关于javascript - 未捕获的类型错误 : Cannot read property 'push' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214553/

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