JS实现数组累加求和

115 阅读1分钟

 求所有图书的总价

待求和数组

const books = [
	{name:"语文",	count:20,	price:50},
	{name:"数学",	count:10,	price:10},
	{name:"英语",    count:50,	price:22}	
]

方式一:for循环

function getTotalPrice(books){
	let totalPrice = 0
	for(let i =0;i<books.length;i++){
		totalPrice += books[i].count*books[i].price
	}
	return totalPrice
}

方式二:map + replace + eval

function getTotalPrice(books){
	const priceMap = books.map(book => book.count*book.price)
	return eval(priceMap.toString().replace(/\,/g,'+'))
}

方式三:reduce

function getTotalPrice(books){
	return books.reduce((pre,cur)=>{
		return pre + cur.count*cur.price
	},0)
}