JavaScript Fundamentals

掌握JavaScript数组的map和filter方法

Spread the love

本文演示了如何有效地使用JavaScript的map()filter()方法,单独使用和组合使用,以高效地处理数组。我们将探讨实际示例,以说明它们在数据操作中的强大功能和多功能性。

目录

JavaScript Map 方法

map()方法是一个高阶函数,它迭代数组中的每个元素并应用提供的回调函数。此函数转换每个元素,map()返回一个包含转换后值的新数组。原始数组保持不变。


const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(number => number * 2); // [2, 4, 6, 8, 10]
console.log(doubledNumbers);
console.log(numbers); // 原始数组不变

JavaScript Filter 方法

filter()方法也迭代数组。但是,它不是转换元素,而是根据回调函数定义的条件选择性地包含元素。回调函数应返回true以包含元素,返回false以排除元素。filter()返回一个仅包含满足条件的元素的新数组。


const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(number => number % 2 === 0); // [2, 4, 6]
console.log(evenNumbers);

Map 和 Filter 方法链式调用

map()filter()的真正强大之处在于它们可以链式调用。这允许以简洁高效的方式执行复杂的数据操作。通常先应用filter()来缩小数组范围,然后应用map()来转换剩余的元素。


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenSquared = numbers
  .filter(number => number % 2 === 0)
  .map(number => number * number); // [4, 16, 36, 64, 100]
console.log(evenSquared);

实际案例:电子商务产品过滤

让我们想象一个电子商务应用程序。我们有一个产品对象的数组:


const products = [
  { name: "Shirt", price: 25, inStock: true, category: "clothing" },
  { name: "Pants", price: 40, inStock: false, category: "clothing" },
  { name: "Shoes", price: 75, inStock: true, category: "shoes" },
  { name: "Hat", price: 15, inStock: true, category: "accessories" },
  { name: "Jacket", price: 60, inStock: true, category: "clothing" }
];

我们只想显示库存中的服装商品名称。我们可以使用filter()map()优雅地实现这一点:


const inStockClothingNames = products
  .filter(product => product.inStock && product.category === "clothing")
  .map(product => product.name);

console.log(inStockClothingNames); // ['Shirt', 'Jacket']

结论

结合使用map()filter()提供了一种强大且易读的JavaScript数组操作方法。这种函数式编程风格促进了更简洁的代码,减少了冗长的循环,并提高了可维护性。记住,这两种方法都返回新的数组,保留了原始数据的不可变性。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注