发布于 2026-01-06 7 阅读
0

简要介绍 map()、filter() 和 reduce() 方法 Map:Filter:Reduce:DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

简要介绍 map()、filter() 和 reduce() 方法

地图:

筛选:

减少:

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

以下是一些开发过程中常用的方法,掌握这些方法至关重要。那么,让我们开始吧!

地图:

map()方法从现有数组创建一个新数组,并将该函数应用于第一个数组的每个元素。

例如。

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

筛选:

filter()方法根据条件语句返回相应的值。它会检查数组中每个元素的条件,如果条件为真则返回该元素的值,否则不返回。

例如。

const numbers = [4, 7, 12, 3];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [4, 12]
Enter fullscreen mode Exit fullscreen mode
const students = [
  { name: 'abc', attendance: 96 },
  { name: 'mno', attendance: 60 },
  { name: 'def', attendance: 89 },
  { name: 'jkl', attendance: 65 },
  { name: 'xyz', attendance: 40 }
];

const eligibleStudent = students.filter(student => student.attendance >= 75);
return eligibleStudent; // [ { name: 'abc', grade: 96 }, { name: 'def', grade: 89}]
Enter fullscreen mode Exit fullscreen mode

减少:

reduce()方法将数组简化为单个值,对数组中的每个元素执行提供的函数。

句法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Enter fullscreen mode Exit fullscreen mode

`total`(初始值,即函数上次返回的值)和 `currentValue`(当前元素的值)是必需参数。`initialValue` 是可选参数,用于设置数组的初始值。如果未提供 `initialValue`,则数组的第一个元素将用作初始值。对空数组调用 `reduce()` 函数且未指定 `initialValue` 将抛出 `TypeError` 异常。

例如

const euros = [29.76, 41.85, 46.5];
const sum = euros.reduce((total, amount) => total + amount); 
console.log(sum)  // 118.11
Enter fullscreen mode Exit fullscreen mode
var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
];

const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0); 
console.log(totalYears) //82
Enter fullscreen mode Exit fullscreen mode

本期内容就到这里。如果你学到了什么,请分享给你的开发者朋友们。欢迎在Twitter上关注我,我会每天发布关于开发和技术方面的推文。祝你编程愉快!👨‍💻❤

文章来源:https://dev.to/arifimran5/brief-touch-on-map-filter-and-reduce-methods-5g41