溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript中如何使用 .map()、.reduce() 和 .filter()方法

發(fā)布時(shí)間:2022-03-11 11:56:17 來(lái)源:億速云 閱讀:143 作者:小新 欄目:編程語(yǔ)言

這篇文章主要為大家展示了“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”這篇文章吧。

舉例介紹三個(gè)最常用的方法:map、reduce 和 filter。

在新冠疫情 之前,我們?nèi)グ屠瓒燃?。于是他們?nèi)コ匈I(mǎi)了些東西。他們買(mǎi)了食物和日用品。但是所有的物品都是歐元,他們想知道每件物品的價(jià)格以及他們食物的人民幣總成本。

鑒于 1 歐元等于 7.18 日元。

以傳統(tǒng)方式,我們將使用經(jīng)典循環(huán)來(lái)完成:

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
現(xiàn)在我們來(lái)使用現(xiàn)在 JavaScript 提供的函數(shù)式編程方法來(lái)實(shí)現(xiàn)這個(gè)計(jì)算。

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 方法將歐元轉(zhuǎn)為日元,使用 filter 過(guò)濾掉非食品的項(xiàng)目,使用 reduce 來(lái)計(jì)算價(jià)格總和。

以上是“JavaScript中如何使用 .map()、.reduce() 和 .filter()方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI