原文:The 7 JS Array Methods you will need in 2021

封面:Photo by kyle smith on Unsplash

Get a great start off your year learning these useful methods. BY Twan Mulder

让你 2021(JS)学习开个好头,来学习这些有用的方法吧~

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!`);

// Result:
["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!"];

A JavaScript code block showing how the map method is used to create a new, modified array of the original one.
A JavaScript code block showing how the map method is used to create a new, modified array of the original one.

这里, .map() 方法就用来创建出了一个新的、更改过的数组。

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

更棒的是,我们可用 .map() 方法处理包含对象的数组。

举一个例子,我们有一堆价格不含税的汽车,然后使用 .map() 添加含税的价格。

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
  }
});

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

JS code block showing how to use the .map() method to create a new array containing the price with tax
JS code block showing how to use the .map() method to create a new array containing the price with tax

总而言之,.map()方法是创建新数组,修改其内容并保持原始数组完整的一种极其通用的方法。

何时用 Array.map()?

当您想要修改现有数组的内容,并将结果存储为新(数组)变量时。


2. Array.filter()

你几乎可以猜到该方法会做什么。

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

就像 .map()方法一样, .filter() 方法将返回一个新数组,并保留原始数组。

还是用汽车来举例,我们根据汽车价格高于某个特定值来过滤数组。

这里,我们有如下汽车(变量/参数):

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

现在,假设我们设置超过 40,000 的即为昂贵(expensive)。

我们可使用 .filter() 方法来过滤出所有 ”cheap“ 和 ”expensive“ 的汽车为两个不同数组。

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

// Result - Expensive Cars
[
  {brand: "Porsche", price: 100000},
  {brand: "Audi", price: 80000}
];

// Result - Cheap Cars
[
  {brand: "Toyota", price: 30000}
];

JS code block showing how to use the filter method to filter cheap/expensive cars from an array.
JS code block showing how to use the filter method to filter cheap/expensive cars from an array.

检查数组中的每个元素是否符合条件,如通过测试,则将其返回到新数组中 —— 太棒了!

何时用 Array.filter()?

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


3. Array.reduce()

现在讲的这个理解上可能会有些棘手。

简单来说,数组调用 .reduce() ,会对数组中的每个元素执行一个函数,累计处理其返回为单个值。

.reduce() 方法将回调函数作为其第一个传参,可选的初始化值作为其第二个传参(若无初始值,则将使用数组中的第一个元素)。回调函数提供了 accumulatorcurrentValue 两个参数来进行累计处理。

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

这里有个简单的例子来展示下 .reduce() 方法的使用:

假设我们要获取一下数组中所有数字的总和。

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

We can then use the .reduce() method to add all these values together.

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

// Result - Total:
235

JS code block showing how to use the reduce method to add up all values of an array.
JS code block showing how to use the reduce method to add up all values of an array.

以上,使用 reduce 方法将数组的所有值相加。

另外, .reduce() 方法可用于展开(多维)数组。有不少方式可以做到这一点,这是其中一种。

const flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( accumulator, currentValue ) => accumulator.concat(currentValue),
  []
)

// Result - Flattened:
[0, 1, 2, 3, 4, 5]

JS code block showing how to use the reduce method to flatten an array.
JS code block showing how to use the reduce method to flatten an array.

何时用 Array.reduce()?

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


4. Array.forEach()

Ah,这个可是经典。

.forEach() 方法就和常规的 for 循环非常相似。

它会循环遍历某一个元素并在其上执行一个函数。 .forEach() 方法的第一个传参是回调函数,这个回调函数包含循环的当前值和索引。

用我们的车车来看以下示例:

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

我们可以循环并打印出一句话,包含品牌名称和汽车价格。

cars.forEach(car => {
  console.log(`The ${car.brand} will cost you ${car.price} before taxes`);
});

// Result:
"The Porsche will cost you 100000 before taxes"
"The Audi will cost you 80000 before taxes"
"The Toyota will cost you 30000 before taxes"

JS code block showing how to use the forEach method to loop over all cars and log text showing its brand and price.
JS code block showing how to use the forEach method to loop over all cars and log text showing its brand and price.

何时用 Array.forEach()?

当你想简单遍历所有数组元素(并执行函数),而无需构造新数组时。


5. Array.find()

.find() 方法看上去非常像之前看到的 .filter() 方法。

就像 .filter() 方法一样,你可以传递一个条件,该条件能匹配出(符合该条件的)数组元素值。

两者的区别在于, .find() 将返回与条件匹配的第一个元素。

以汽车示例为例,让我们使用.find() 方法获得数组中遇到的第一辆昂贵的汽车。

const cars = [
  {brand: "Porsche", price: 100000},
  {brand: "Audi", price: 80000},
  {brand: "Toyota", price: 30000}
];
const expensiveCar = cars.find(car => car.price >= 40000);

// Result - Expensive Car:
{brand: "Porsche", price: 100000}

JS code block showing how to use the find method to find the first “expensive” car in an array.
JS code block showing how to use the find method to find the first “expensive” car in an array.

何时用 Array.find()?

当你需要获取数组中满足特定测试的第一个元素时。


6. Array.every()

也许你已经可以猜到此方法会做什么。

.every() 方法将检查数组中的每个元素是否通过提供的条件。

如果所有数组元素通过了这个条件,会返回 true 。如果没有,会返回 false

举例说明,我们可以使用.every() 方法来检测是否所有汽车实在近五年内制造的。

const cars = [
  {brand: "Porsche", price: 100000, builtIn: 2018},
  {brand: "Audi", price: 80000, builtIn: 2019},
  {brand: "Toyota", price: 30000, builtIn: 2019}
];
const carsYoungerThanFiveYears = cars.every(car => car.builtIn >= 2016);

// Result - Younger than 5 Years:
true

JS code block showing how to use the every method to determine if all cars are built within 5 years.
JS code block showing how to use the every method to determine if all cars are built within 5 years.

何时用 Array.every()?

当您要确认数组的每个元素是否都通过显式定义的条件时。


7. Array.some()

.some() 方法类似 .every() 方法,但是不同于所有元素都需通过测试,存在至少一个元素通过测试,该方法就会返回 true。

.some() 方法如果找到了一个满足条件的数组元素,就会停止并返回 true。但如果遍历之后仍未找到(满足条件的),则返回 false。

再来看下我们的车车数组,但是这次我们来查下是否有车车龄超过 5年。

const cars = [
  {brand: "Porsche", price: 100000, builtIn: 2018},
  {brand: "Audi", price: 80000, builtIn: 2019},
  {brand: "Toyota", price: 30000, builtIn: 2019}
];
const carsOlderThanFiveYears = cars.some(car => car.builtIn < 2016);

// Result - Older than 5 Years:
false

JS code block showing how to use the some method to check if any of the cars is older than 5 years.
JS code block showing how to use the some method to check if any of the cars is older than 5 years.

何时用 Array.some()?

当您要确认数组中是否存在元素能通过显式定义的条件时。

总结

🤩 JavaScript 给我们提供了很多处理数组的不同方法。使用这些方法,你将能提升 JS 开发技能,并使代码库更具可维护性。

😌 也许你再也不会碰 for 循环了。

我希望你今天能学到一些新东西。

想要继续提升你的 JS 技能?看看原作者的其他文章

【译】10个JS单行代码,可加入你的开发兵器库

or What’s the difference between Event Handlers & addEventListener in JS

Have a nice day! 😄