Fetching contributors…
Cannot retrieve contributors at this time
199 lines (124 sloc) 3.31 KB

# 数组

## Map 介绍

### 语法

`array.map(callback[, thisArg])`

### 参数

#### callback

currentValue

callback 的第一个参数，数组中当前被传递的元素。

index

callback 的第二个参数，数组中当前被传递的元素的索引。

array

callback 的第三个参数，调用 map 方法的数组。

### 例题

https://www.codewars.com/kata/double-char

Given a string, you have to return a string in which each character (case-sensitive) is repeated once.

```doubleChar("String") ==> "SSttrriinngg"

doubleChar("Hello World") ==> "HHeelllloo  WWoorrlldd"

doubleChar("1234!_ ") ==> "11223344!!__  "```

Good Luck!

`const doubleChar = str => str.split('').map(i => i.repeat(2)).join('');`

## Reduce 介绍

### 语法

`arr.reduce(callback,[initialValue]);`

accumulator

currentValue

currentIndex

array

### 例题

https://www.codewars.com/kata/beginner-reduce-but-grow

Given and array of integers (x), return the result of multiplying the values together in order. Example:

``````[1, 2, 3] --> 6
``````

For the beginner, try to use the reduce method - it comes in very handy quite a lot so is a good one to know.

Array will not be empty.

`const grow = x => x.reduce((r, i) => r * i, 1);`

## 遍历用Map还是For

### 对比

#### map

```[1,2,3,4,5].map(x => x+1)
// [ 2, 3, 4, 5, 6 ]```

### Benchmark测试

benchmark脚本：

```suite('iterator', function () {
bench('for', function () {
const a = [1, 2, 3, 4, 5];
for (let i = 0; i < a.length; i++) {
// nothing
}
});
bench('foreach', function () {
const a = [1, 2, 3, 4, 5];
a.forEach(function (d) {
// nothing
});
});
bench('for of', function () {
const a = [1, 2, 3, 4, 5];
for (let i of a) {
// nothing
}
});
bench('map', function () {
const a = [1, 2, 3, 4, 5];
a.map(x => x);
});
});```

```                      iterator
50,038,931 op/s » for
8,980,276 op/s » foreach
8,990,758 op/s » for of
1,713,807 op/s » map

Suites:  1
Benches: 4
Elapsed: 5,710.33 ms```

### 结论

`foreach``for ... of` 差不多。

`map` 性能最低。

## 生成一个 m 到 n 的数组

```const list = (m, n) =>
new Array(n - m + 1).fill(0).map((_, i) => m + i);```
You can’t perform that action at this time.