freeCodeCamp/guide/chinese/javascript/es6/map-function/index.md

25 lines
725 B
Markdown
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
title: Map Function
localeTitle: 地图功能
---
## 地图功能
`map()`函数用于从现有数组创建新数组,将函数应用于第一个数组的每个元素。
map函数的原始语法是
```javascript
let new_arr = arr.map(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
})
```
### 示例ES6
```javascript
const myArray_1 = [1, 2, 3, 4];
const myArray_2 = myArray_1.map(el => el * 2);
```
`myArray_2`将包含以下元素: `[2, 4, 6, 8]`
`map()`是`Array`对象的一个方法因此要将该函数传递给一个可迭代对象必须使该对象成为一个Array。