JavaScript 提供了许多处理数组的不同方法。在几分钟内为您介绍 7 个基本且常用的数据方法,以提高您的 JS 开发技能。

1. Array.map()

当你在数组上使用 map() 方法的时候,它将在原始的数组创建一个新的数组。

这个 map() 方法接受一个参数,这个参数是个函数,这个函数可以去循环或遍历数组中的每个元素,也可以对里面的每个元素进行修改,然后组合返回出一个新的数组。

当你想在一个数组中把它的元素修改或更新,然后存储成一个新的数组的时候,这个 .map() 方法就会派上用场。

假设我们有一个包含汽车品牌的数组:

const cars = ["Porsche", "Audi", "BMW", "Volkswagen"];

当然,我们认为所有的车都很酷,我们想添加一些文字来表达这一点。 我们可以使用 .map() 方法:

const coolCars = cars.map((car) => `${car} is a pretty cool car brand!`);

// 结果:
[
  "Porsche is a pretty cool car brand!",
  "Audi is a pretty cool car brand!",
  "BMW is a pretty cool car brand!",
  "Volkswagen is a pretty cool car brand!",
];

这里, 这个 map() 方法用于创建新的修改后的数组

太棒了! 那个 map() 方法创建了一个新数组,并将文本添加到每个元素。

有时候数组包含对象(object),我们又应该如何操作呢?

让我们看下面的例子,给这个汽车添加价格属性,变成对象的情况:

const carsWithPrice = [
  { brand: "Porsche", price: 100000 },
  { brand: "Audi", price: 80000 },
];

const carsWithPriceAndTax = cars.map((carObject) => {
  return {
    // Return the original car object
    ...carObject,
    // but also add a new value containing the price with tax
    priceWithTax: carObject.price * 1.2,
  };
});

// 结果:
[
  { brand: "Porsche", price: 100000, priceWithTax: 120000 },
  { brand: "Audi", price: 80000, priceWithTax: 96000 },
];

使用 map() 方法以创建包含含税价格的新数组

总之,map() 方法是一种非常常用的方法,用于创建新数组、修改其内容并保持原始数组不变。

何时使用 Array.map()?

当您想要修改现有数组的内容并将结果存储为新数组的时候。

2. Array.filter()

你几乎猜到这个方法是什么的。

这个 .filter() 方法允许您根据特定条件获取数组中的元素。

就像 map() 方法一样,它将返回一个新数组并保持原始数组不变。

例如,使用汽车的例子,我们可以用基于汽车价格高于某个值来过滤数组。

在这里,我们有所有可用的汽车:

const cars = [
  { brand: "Porsche", price: 100000 },
  { brand: "Audi", price: 80000 },
  { brand: "Toyota", price: 30000 },
];

现在,假设所有价值 40,000 或更多的汽车都很贵。

我们可以使用 filter() 方法所有 “便宜” 和 “昂贵” 的汽车。

const expensiveCars = cars.filter((car) => car.price >= 40000);
const cheapCars = cars.filter((car) => car.price < 40000);

// 结果 - 贵车
[
  { brand: "Porsche", price: 100000 },
  { brand: "Audi", price: 80000 },
];

// 结果 - 便宜车
[{ brand: "Toyota", price: 30000 }];

使用过滤方法从数组中过滤 "便宜"、"昂贵"的汽车

检查数组的每个元素,看它是否符合标准,如果通过测试,它将在新数组中返回。

何时使用 Array.filter()?

当您想要从数组中删除不符合特定条件/条件的元素时。

3. Array.reduce()

现在这个可能有点难以理解。

简而言之,在数组中调用 .reduce() 方法,它会通过执行一个函数或方法来循环遍历数组中的每个元素,最终返回出一个值。

那个 reduce() 方法将回调函数作为其第一个参数,并将可选的初始值作为其第二个参数。如果未提供初始值,则使用数组的第一个值。这个回调函数将提供 accumulatorcurrentValue 参数用于执行 reduce 计算。

我知道这可能有点复杂,但没关系。

这里有一个简单的例子来展示 reduce() 方法:

假设我们想要获取数组中所有数字的总值。

const numbers = [13, 65, 29, 81, 47];

然后,我们可以使用 reduce () 方法将所有这些值加在一起。

const total = numbers.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  0
);

// 结果 - 总数:
235;

使用 reduce 方法将数组的所有值相加

使用的另一种 reduce() 函数的方式是展平数组,已经有很多方法可以做到这一点,这就是其中之一。

const flattened = [
  [0, 1],
  [2, 3],
  [4, 5],
].reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])[
  // Result - Flattened:
  (0, 1, 2, 3, 4, 5)
];

使用 reduce 方法展平数组

何时使用 Array.reduce()?

当您想要通过操作数组的值将数组转换为单个值的时候。