目錄
map : Transform Every Element in an Array
filter : Keep Only What You Need
reduce : Build Up a Single Value
Bonus: Chaining Methods Together
首頁 web前端 js教程 掌握JavaScript數組方法:``map`,`filt filter''和`reste''

掌握JavaScript數組方法:``map`,`filt filter''和`reste''

Aug 03, 2025 am 05:54 AM
數組方法

JavaScript的數組方法map、filter和reduce用於編寫清晰、函數式的代碼。 1. map用於轉換數組中的每個元素並返回新數組,如將攝氏溫度轉為華氏溫度;2. filter用於根據條件篩選元素並返回符合條件的新數組,如獲取偶數或活躍用戶;3. reduce用於累積結果,如求和或統計頻次,需提供初始值並返回累加器;三者均不修改原數組,可鍊式調用,適用於數據處理與轉換,提升代碼可讀性與功能性。

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

JavaScript's array methods like map , filter , and reduce are essential tools for writing clean, functional, and readable code. Once you understand how they work and when to use them, you'll find yourself reaching for for loops much less often. Let's break down each method with practical examples and clear explanations.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

map : Transform Every Element in an Array

Use map when you want to transform each item in an array and return a new array with the updated values.

It doesn't change the original array — it creates a new one.

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`

Example: Convert temperatures from Celsius to Fahrenheit

 const celsius = [0, 10, 20, 30, 40];

const fahrenheit = celsius.map(temp => (temp * 9/5) 32);

console.log(fahrenheit); // [32, 50, 68, 86, 104]

Key points:

Mastering JavaScript Array Methods: `map`, `filter`, and `reduce`
  • Always returns a new array of the same length .
  • Great for formatting data (eg, transforming API responses).
  • Common in React for rendering lists.

? Think of map as a factory line: each item goes in, gets processed, and comes out changed.


filter : Keep Only What You Need

Use filter when you want to select a subset of items based on a condition.

It returns a new array with only the elements that pass the test.

Example: Get only even numbers

 const numbers = [1, 2, 3, 4, 5, 6, 7, 8];

const evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4, 6, 8]

Example: Find active users

 const users = [
  { name: 'Alice', active: true },
  { name: 'Bob', active: false },
  { name: 'Charlie', active: true }
];

const activeUsers = users.filter(user => user.active);

console.log(activeUsers);
// [{ name: 'Alice', active: true }, { name: 'Charlie', active: true }]

Key points:

  • The returned array can be shorter than the original.
  • The callback must return true or false .
  • You can chain it with other methods.

?️ filter is perfect when you're searching, cleaning data, or applying user filters in UIs.


reduce : Build Up a Single Value

Use reduce when you want to accumulate a result — like a sum, object, or nested structure — from an array.

It's the most powerful but also the most misunderstood.

Example: Sum all numbers

 const nums = [1, 2, 3, 4];

const sum = nums.reduce((accumulator, current) => accumulator current, 0);

console.log(sum); // 10

How it works:

  • accumulator holds the result so far.
  • current is the current element.
  • The second argument ( 0 ) is the initial value of the accumulator.

Example: Count occurrences (grouping)

 const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) 1;
  return acc;
}, {});

console.log(count);
// { apple: 3, banana: 2, orange: 1 }

Key points:

  • You can return any type: number, object, array, etc.
  • Always return the accumulator (or updated state) in the callback.
  • Initial value is optional but highly recommended to avoid bugs.

? reduce is like folding a list into a single value — imagine gathering scattered papers into one stack.


Bonus: Chaining Methods Together

One of the best parts? You can chain these methods for powerful data processing.

Example: Get total price of expensive books

 const books = [
  { title: 'JS Guide', price: 25 },
  { title: 'React Tips', price: 30 },
  { title: 'CSS Tricks', price: 15 },
  { title: 'Node Handbook', price: 35 }
];

const total = books
  .filter(book => book.price > 20) // Keep expensive books
  .map(book => book.price) // Extract prices
  .reduce((sum, price) => sum price, 0); // Sum them

console.log(total); // 90

This is readable, functional, and avoids manual loops.


These three methods — map , filter , and reduce — are the building blocks of functional programming in JavaScript. Use them to write clearer, more predictable code. They might feel awkward at first, but once they click, you'll wonder how you ever coded without them.

Basically, just remember:

  • map → change each item
  • filter → pick some items
  • reduce → boil it all down

And don't forget: they all return new arrays (or values), so keep things immutable and safe.

以上是掌握JavaScript數組方法:``map`,`filt filter''和`reste''的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Laravel 教程
1604
29
PHP教程
1510
276
了解PHP中陣列的定義方法 了解PHP中陣列的定義方法 Mar 13, 2024 pm 02:09 PM

標題:PHP中數組的定義方法及具體程式碼範例PHP中數組是一種非常重要的資料類型,能夠儲存多個值,並且可以根據索引或鍵值進行存取。在PHP中,陣列有多種定義方法,本文將介紹其中常用的幾種方法,並提供具體的程式碼範例來幫助理解。 1.索引數組索引數組是最常見的數組類型,其元素透過數字索引進行存取。在PHP中,可以使用array()函數或簡化的[]符號來定義

深入了解Go語言數組方法的實戰應用 深入了解Go語言數組方法的實戰應用 Mar 24, 2024 pm 12:36 PM

Go語言作為一種快速、簡潔和高效的程式語言,擁有強大的工具和功能來處理陣列。在Go語言中,陣列是一種固定長度的資料結構,它可以儲存一組相同類型的資料元素。本文將探討Go語言中陣列的方法,並提供具體的實戰應用範例。 1.宣告和初始化陣列在Go語言中,宣告和初始化一個陣列可以透過以下方式進行://宣告一個包含5個整數的陣列vararr[5]int//

掌握Go語言數組方法的常見問題與解決方案 掌握Go語言數組方法的常見問題與解決方案 Mar 23, 2024 pm 09:21 PM

掌握Go語言數組方法的常見問題與解決方案在Go語言中,數組是一種基本的資料結構,它由固定長度的相同資料類型的元素組成。在編寫Go程式時,我們經常使用陣列來儲存一組資料。然而,由於數組在Go語言中的特性和限制,有些問題在處理數組時會比較棘手。本文將介紹一些常見的數組問題以及相應的解決方案,並提供具體的程式碼範例。問題一:如何宣告和初始化數組?在Go語言中,可以

利用Array.Prototype方法用於JavaScript中的數據操作 利用Array.Prototype方法用於JavaScript中的數據操作 Jul 06, 2025 am 02:36 AM

JavaScript數組內置方法如.map()、.filter()和.reduce()可簡化數據處理;1).map()用於一對一轉換元素生成新數組;2).filter()按條件篩選元素;3).reduce()用於聚合數據為單一值;使用時應避免誤用導致副作用或性能問題。

某些()和每個()陣列方法有什麼區別? 某些()和每個()陣列方法有什麼區別? Jun 25, 2025 am 12:35 AM

一些()returnStrueifatLeastOnelementPasseStestest,wherevery()returnstRueonlyifalleyspass.1.Some()()excesseforexistEnceCheckSslikeSlikeValidativeActiveActiveAsevalikeUserOusorOut-of-of-of-Stockproductucts.2.every()

Reled()陣列方法如何工作,什麼是好的用例? Reled()陣列方法如何工作,什麼是好的用例? Jul 07, 2025 am 01:33 AM

Thereduce()methodinJavaScriptisapowerfularraytoolthatreducesanarraytoasinglevaluebyapplyingareducerfunction.1.Ittakesanaccumulatorandcurrentvalueasrequiredparameters,andoptionallyaninitialvalue.2.Commonusesincludecalculatingtotals,groupingdata,flatte

高級JavaScript數組方法用於數據轉換 高級JavaScript數組方法用於數據轉換 Jul 16, 2025 am 02:23 AM

JavaScript的數組方法如map、filter和reduce能有效簡化數據處理。 1.map用於轉換數組元素,返回新數組,例如提取字段或修改格式;2.filter用於篩選符合條件的元素,返回新數組,適合過濾無效值或特定條件數據;3.reduce用於聚合操作,如求和或統計,需注意設置初始值並正確返回累積器。這些方法不改變原數組,支持鍊式調用,提升代碼可讀性和維護性。

掌握JavaScript數組方法:``map`,`filt filter''和`reste'' 掌握JavaScript數組方法:``map`,`filt filter''和`reste'' Aug 03, 2025 am 05:54 AM

JavaScript的數組方法map、filter和reduce用於編寫清晰、函數式的代碼。 1.map用於轉換數組中的每個元素並返回新數組,如將攝氏溫度轉為華氏溫度;2.filter用於根據條件篩選元素並返回符合條件的新數組,如獲取偶數或活躍用戶;3.reduce用於累積結果,如求和或統計頻次,需提供初始值並返回累加器;三者均不修改原數組,可鍊式調用,適用於數據處理與轉換,提升代碼可讀性與功能性。

See all articles