数组

Map 介绍

语法

array.map(callback[, thisArg])

参数

callback

原数组中的元素经过该方法后返回一个新的元素。

currentValue

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

index

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

array

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

thisArg

执行 callback 函数时 this 指向的对象。

返回值

由回调函数的返回值组成的新数组。

例题

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.

Good Luck!

答案:

Reduce 介绍

语法

参数

callback

执行数组中每个值的函数,包含四个参数:

accumulator

上一次调用回调返回的值,或者是提供的初始值(initialValue)

currentValue

数组中正在处理的元素

currentIndex

数据中正在处理的元素索引,如果没有提供initialValues,默认从0开始

array

调用 reduce 的数组

initialValue

作为第一次调用 callback 的第一个参数。

返回值

函数累计处理的结果。

例题

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:

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.

答案:

遍历用Map还是For

同是遍历,但实际有很大不同。

对比

map

改变自身。

for

只是循环。

Benchmark测试

benchmark脚本:

测试结果:

结论

单凭循环 for 最可靠。

foreachfor ... of 差不多。

map 性能最低。

生成一个 m 到 n 的数组

用 ES6 的 Fill 特性可以避免 new Array(N) 无法被 Map 的问题。

Last updated

Was this helpful?