![](/img/trans.png)
[英]How to remove an element from an array at particular position in angularjs/javascript
[英]JavaScript: how to remove a particular element from an array
我正在嘗試使用香草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
,它將調用parent Class 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.