gpt4 book ai didi

JavaScript:如何从数组中删除特定元素

转载 作者:行者123 更新时间:2023-12-01 01:11:56 27 4
gpt4 key购买 nike

我正在尝试使用普通 JavaScript 和 OOJS 概念创建一个购物车。

let inventory = [
{ item: "apples", price: 19.95, qty: 50 },
{ item: "oranges", price: 20.99, qty: 40 },
{ item: "pineapples", price: 40.0, qty: 60 },
{ item: "lemons", price: 10.12, qty: 100 }
];

function MyBasket(inventory) {
this.totalItems = [];
}

MyBasket.prototype.addItems = function(item, price, qty) {
this.totalItems.push({ item: item, price: price, qty: qty });
};

MyBasket.prototype.removeItems = function(item, price, qty) {
// write code here.
this.inventory = this.inventory.filter(function(el) {
if (
el.item == item &&
el.price == price &&
el.qty == qty
) return false;
return true;
});
};

MyBasket.prototype.updateInventory = function() {
cart.totalItems.forEach(i => {
const item = inventory.find(o => o.item === i.item);
if (item) item.qty -= i.qty;
});
}

MyBasket.prototype.cartItems = function() {
return this.totalItems;
};

MyBasket.prototype.totalAmount = function() {
return this.totalItems.reduce((acc, item) => {
return acc + item.price * item.qty;
}, 0);
};

var cart = new MyBasket();

cart.addItems("apples", 19, 2);


cart.addItems("oranges", 20, 3);
cart.addItems("lemons", 5, 4);
cart.updateInventory();
console.log("updated inventory", inventory);

cart.removeItems('lemons',10.12,100);
console.log("cart items", cart.cartItems());

console.log("total Amount", cart.totalAmount());

cart.updateInventory();
console.log("updated inventory", inventory);

以上是应用程序的js代码。稍后我将为它创建 UI 并使用 eventListener 来调用我的父类 MyBasket()

问题如何从购物车中删除特定商品?该项目可能位于数组的第一个、最后一个或中间的某个位置。

最佳答案

使用过滤器从库存中获取元素,并使用拼接从库存中删除该元素

let inventory = [
{ item: "apples", price: 19.95, qty: 50 },
{ item: "oranges", price: 20.99, qty: 40 },
{ item: "pineapples", price: 40.0, qty: 60 },
{ item: "lemons", price: 10.12, qty: 100 }
];

function MyBasket(inventory) {
this.totalItems = [];
}

MyBasket.prototype.addItems = function(item, price, qty) {
this.totalItems.push({ item: item, price: price, qty: qty });
console.log(this.totalItems)
};

MyBasket.prototype.removeItems = function(item, price, qty) {
// write code here.
var a=inventory.filter(e=>e.item==item);
inventory.splice(inventory.indexOf(a),1);
console.log(inventory)
};

MyBasket.prototype.updateInventory = function() {
cart.totalItems.forEach(i => {
const item = inventory.find(o => o.item === i.item);
if (item) item.qty -= i.qty;
});
}

MyBasket.prototype.cartItems = function() {
return this.totalItems;
};

MyBasket.prototype.totalAmount = function() {
return this.totalItems.reduce((acc, item) => {
return acc + item.price * item.qty;
}, 0);
};

var cart = new MyBasket();
cart.addItems('s',23,43);
cart.removeItems('lemons',10.12,100);

关于JavaScript:如何从数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085512/

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