这篇文章主要为大家展示了“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”这篇文章吧。
举例介绍三个最常用的方法:map、reduce 和 filter。
在新冠疫情 之前,我们去巴黎度假。于是他们去超市买了些东西。他们买了食物和日用品。但是所有的物品都是欧元,他们想知道每件物品的价格以及他们食物的人民币总成本。
鉴于 1 欧元等于 7.18 日元。
以传统方式,我们将使用经典循环来完成:
const items = [
{
name: 'pineapple',
price: 2,
type: 'food'
},
{
name: 'beef',
price: 20,
type: 'food'
},
{
name: 'advocate',
price: 1,
type: 'food'
},
{
name: 'shampoo',
price: 5,
type: 'other'
}
]
let sum = 0
const itemsInYuan = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
item.price *= 7.18
itemsInYuan.push(item)
if (item.type === 'food') {
sum += item.price
}
}
console.log(itemsInYuan)
/*
[
{ name: 'pineapple', price: 14.36, type: 'food' },
{ name: 'beef', price: 143.6, type: 'food' },
{ name: 'advocate', price: 7.18, type: 'food' },
{ name: 'shampoo', price: 35.9, type: 'other' }
]
*/
console.log(sum) // 165.14
现在我们来使用现在 JavaScript 提供的函数式编程方法来实现这个计算。
const itemsInYuan = items.map(item => {
const itemInYuan = { ...item }
itemInYuan.price *= 7.18
return itemInYuan
})
const sum = itemsInYuan.filter(item => item.type === 'food').reduce((total, item) => total + item.price, 0)
上述示例使用 map 方法将欧元转为日元,使用 filter 过滤掉非食品的项目,使用 reduce 来计算价格总和。
以上是“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/31555445/viewspace-2222297/