markdown 高阶函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 高阶函数相关的知识,希望对你有一定的参考价值。

## Higher-Order Functions

Higher order functions are functions that operate on other functions, either by taking them as arguments or by returning them. In simple words, A Higher-Order function is a function that receives a function as an argument or returns the function as output.

For example, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into the language.

### Higher-Order Functions in Action
Let’s take a look at some examples of built-in higher-order functions and see how it compares to solutions where we aren’t using Higher-Order Functions.

### Array.prototype.map
The map() method creates a new array by calling the callback function provided as an argument on every element in the input array. The map() method will take every returned value from the callback function and creates a new array using those values.

The callback function passed to the map() method accepts 3 arguments: element, index, and array.

Let’s look at some examples:

### Example 1
Let’s say we have an array of numbers and we want to create a new array which contains double of each value of the first array. Let’s see how we can solve the problem with and without Higher-Order Function.

Without Higher-order function
```sh
const arr1 = [1, 2, 3];
const arr2 = [];

for(let i = 0; i < arr1.length; i++) {
  arr2.push(arr1[i] * 2);
}

// prints [ 2, 4, 6 ]
console.log(arr2);
```

### With Higher-order function map

```sh
const arr1 = [1, 2, 3];
const arr2 = arr1.map(function(item) {
  return item * 2;
});
console.log(arr2);
```

We can make this even shorter using the arrow function syntax:

```sh
const arr1 = [1, 2, 3];
const arr2 = arr1.map(item => item * 2);
console.log(arr2);
```

### Example 2
Let’s say we have an array containing the birth year of different persons and we want to create an array that contains their ages. For example:

Without Higher-order function

```sh
const birthYear = [1975, 1997, 2002, 1995, 1985];
const ages = [];
for(let i = 0; i < birthYear.length; i++) {
  let age = 2018 - birthYear[i];
  ages.push(age);
}
// prints [ 43, 21, 16, 23, 33 ]
console.log(ages);
```

With Higher-order function map

```sh
const birthYear = [1975, 1997, 2002, 1995, 1985];
const ages = birthYear.map(year => 2018 - year);
// prints [ 43, 21, 16, 23, 33 ]
console.log(ages);
```

以上是关于markdown 高阶函数的主要内容,如果未能解决你的问题,请参考以下文章

markdown 高阶关数

MarkDown语法

MarkDown语法-使用博客园的markDown编辑

高阶组件&&高阶函数

Python 学习笔记 -- 内嵌函数闭包匿名函数高阶函数map高阶函数filter高阶函数reduce

Kotlin的高阶函数和常用高阶函数