# 高阶函数替换JavaScript中的循环

> JavaScript新方法代替传统循环方法操作。本篇文章对比介绍实际场景方法运用。

Author: DeathGhost
Published: 2020-05-26 21:51:01
Category: javascript
Canonical: https://www.deathghost.cn/article/javascript/75
Keywords: JavaScript, 函数, 高阶函数, 替换, 循环, ES6, some, every, filter, reduce

## 为什么高阶函数替换循环？

使用高阶函数将使您的代码可以使你的代码可读性更强，易于理解，便于调试。

![JavaScript高阶函数替换循环](https://www.deathghost.cn/public/upload/article/2020/05/26/1590502456525142.jpg)

JavaScript高阶函数替换循环

场景示例

### 一、遍历数组元素，返回一个修改后的新数组。

e.g. 将数组元素转换为大写

循环方式：

const animal = ['dog', 'cat', 'monkey', 'tiger'];
let upperCaseAnimal = [];
for(const item of animal) {
  upperCaseAnimal.push(item.toUpperCase());
}
// 输出
0: "DOG"
1: "CAT"
2: "MONKEY"
3: "TIGER"
不用循环

const animal = ['dog', 'cat', 'monkey', 'tiger'];
let upperCaseAnimal = animal.map(item => item.toUpperCase());
结果也是一样。

### 二、遍历数组元素，并执行某一方法。

循环：

const animal = ['dog', 'cat', 'monkey', 'tiger'];
function output(name) {
  console.log(name);
}
for (const item of animal) {
  output(item);
}
不用循环：

const animal = ['dog', 'cat', 'monkey', 'tiger'];
function output(name) {
  console.log(name);
}
animal.forEach(name=> output(name));

### 三、数组元素过滤。

e.g. 返回数组中的奇数。

循环：

const numbers = [1, 2, 3, 4, 5];
const odd = [];
for (const item of numbers) {
  if ( item % 2 ) {
    odd.push(item);
  }
}
不用循环：

const numbers = [1, 2, 3, 4, 5];
const odd = numbers.filter(item => item % 2);
// 输出结果
[1, 3, 5]

### 四、数组元素求和。

循环：

const numbers = [1, 2, 3, 4, 5];
let result = 0;
for (const item of numbers) {
  result  = item;
}
不用循环：

const numbers = [1, 2, 3, 4, 5];
let result = numbers.reduce((acc, val) => acc + val, 0);
// 输出结果
15

### 五、检测数组中的元素是否满足指定条件。

循环：

const numbers = [1, 2, 3, 4, 5];
for (const item of numbers) {
  if (item === 3) {
    console.log('Y');
  }
}
不用循环：

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.some(item => item === 3));
补充：

some() 方法用于检测数组中的元素是否满足指定条件（函数提供）。

some() 方法会依次执行数组的每个元素：

如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测。

如果没有满足条件的元素，则返回false。

注意： some() 不会对空数组进行检测。

注意： some() 不会改变原始数组。

### 六、检查数组中每个元素是否均满足指定条件。

循环：

const numbers = [1, 2, 3, 4, 5];
for (const item of numbers) {
  if (item > 0) {
    console.log(item);
  }
}
不用循环：

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.every(item => item > 0));
补充：

every() 方法用于检测数组所有元素是否都符合指定条件（通过函数提供）。

every() 方法使用指定函数检测数组中的所有元素：

如果数组中检测到有一个元素不满足，则整个表达式返回 false ，且剩余的元素不会再进行检测。

如果所有元素都满足条件，则返回 true。

注意： every() 不会对空数组进行检测。

注意： every() 不会改变原始数组。

好了，就到这里，晚安！🌛

## Related

- Previous: [初略Web API Notification 桌面通知](https://www.deathghost.cn/article/javascript/74)
- Next: [JS原生的深拷贝API structuredClone()](https://www.deathghost.cn/article/javascript/120)
