簡體   English   中英

如何.filter和.reduce javascript數組對象

[英]How to .filter and .reduce javascript array object

WebDev學生。 我在使用.filter + .reduce數組方法和鏈接返回兩個項目的總成本時遇到問題。 關於該主題的Codeburst.io超級有幫助,但是由於我要針對屬性:數組中的值,因此我需要有關如何應用於此特定練習的指導。

這是減少代碼量的一種練習。因此,與使用for循環遍歷數組相比,我需要對.filter through和.reduce應用一個或多個方法來返回其中每個項目的總成本。數組。 .price

使用shopCart變量,創建一個使用shopCart變量並將兩個項目的總成本作為total變量返回的函數。 在“ //下面的代碼”之后添加代碼。

 var shopCart = [ { id: 0, name: 'Womens Shirt', price: 30, size: 'Small' }, { id: 1, name: 'childs shirt', price: 12, size: 'Large' } ] function getCost(items){ let total = 0; // code below // code above return total; } getCost(shopCart) < --- Add let cost = getCost(shopCart); < ---OMIT console.log(cost); < -- OMIT 

請重新審核-代碼已修改。

這是一種更明確的方法。

function sum(nums) {
  return nums.reduce((a, b) => a + b)
}

const prices = items.map(item => item.price)
const total = sum(prices)

您可以使用迭代來執行此操作,例如for循環。 getCost函數中,我們有一個初始值為零的總變量。 然后,對於items數組中的每個元素,將使用價格來累計總數。 但是,使用reduce方法類似地可以使用此功能。

 var shopCart = [ { id: 0, name: 'Womens Shirt', price: 30, size: 'Small' }, { id: 1, name: 'childs shirt', price: 12, size: 'Large' } ]; function getCost(items) { var total = 0; items.forEach(e => total += e.price); return total; } let cost = getCost(shopCart); // 42 let costWithReduce = shopCart.reduce((a, c) => a + c.price, 0); // 42 console.log(cost, costWithReduce); 

您可以使用array#reduce total ,您可以添加每個對象的price

 var shopCart = [{id: 0,name: 'Womens Shirt',price: 30,size: 'Small'},{id: 1,name: 'childs shirt',price: 12,size: 'Large'}]; function getCost(items){ return items.reduce(function(total, obj){ return total + obj.price; }, 0); } let cost = getCost(shopCart); console.log(cost); 

 var shopCart = [{id: 0,name: 'Womens Shirt',price: 30,size: 'Small'},{id: 1,name: 'childs shirt',price: 12,size: 'Large'}]; function getCost(items){ return items.reduce((total, {price}) => total + price, 0); } let cost = getCost(shopCart); console.log(cost); 

確實與其他人回答相同,但在必填參數之內。

 var shopCart = [ { id: 0, name: 'Womens Shirt', price: 30, size: 'Small' }, { id: 1, name: 'childs shirt', price: 12, size: 'Large' } ] function getCost(items){ let total = 0; // code below total = items.reduce((sum, item) => sum + item.price, total); // code above return total; } let cost = getCost(shopCart); console.log(cost); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM