如何从阵列中删除所有项目并显示它?

时间:2020-11-29 19:36:41

I have a mock webstore I'm making for a project and I can't seem to get my empty cart button working. The user clicks add or remove item to add or remove items from the cart, but my button to empty the cart isn't working.

我有一个模拟的网店,我正在为一个项目做,我似乎无法让我的空车按钮工作。用户单击添加或删除项目以添加或从购物车中删除项目,但我清空购物车的按钮不起作用。

<button type="button" onclick="removeAll()" style="color:black">Empty Cart</button>

I've tried removing each item individually with one button click but it only removed the first item in the array.

我已经尝试单击一个按钮单独删除每个项目,但它只删除了数组中的第一个项目。

function removeItem(itemIndex) { //remove item from cart
cart.remove(itemIndex);
cart.display();
}

function removeAll(itemIndex) { //removes all items from cart
removeItem(0);
removeItem(1);
removeItem(2);
}

function Cart (holder, items) {
this.holder = holder;
this.items = items;
this.quantities = Array();
for (var i=0; i<items.length; i++)
this.quantities[i] = 0;

this.add = function (index) {
this.quantities[index]++;
}
this.remove = function (index) {
if (this.quantities[index] > 0)
this.quantities[index]--;
}

Any help would be appreciated, thanks

任何帮助将不胜感激,谢谢

2 个解决方案

#1


1  

Looking at that code, you want removeAll to be:

查看该代码,您希望removeAll为:

function removeAll() { //removes all items from cart
    var n;
    for (n = 0; n < cart.quantities.length; ++n) {
        cart.quantities[n] = 0;
    }
    cart.display();
}

...though it would probably make sense to put removeAll on Cart.prototype (adjusted accordingly).

...虽然将removeAll放在Cart.prototype上可能是有意义的(相应调整)。

#2


0  

Why not just reset the array?

为什么不重置阵列?

function removeAll() {
    this.items = [];
    this.quantities = [];
}

#1


1  

Looking at that code, you want removeAll to be:

查看该代码,您希望removeAll为:

function removeAll() { //removes all items from cart
    var n;
    for (n = 0; n < cart.quantities.length; ++n) {
        cart.quantities[n] = 0;
    }
    cart.display();
}

...though it would probably make sense to put removeAll on Cart.prototype (adjusted accordingly).

...虽然将removeAll放在Cart.prototype上可能是有意义的(相应调整)。

#2


0  

Why not just reset the array?

为什么不重置阵列?

function removeAll() {
    this.items = [];
    this.quantities = [];
}