数组
求所有图书的总价
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
}
2.map + replace + eval
function getTotalPrice(books){
const priceMap = books.map(book => book.count*book.price)
return eval(priceMap.toString().replace(/\,/g,'+'))
}
3.reduce
function getTotalPrice(books){
return books.reduce((pre,cur)=>{
return pre + cur.count*cur.price
},0)
}
就比较典型的几个方法~