JavaScript学习笔记-Map&Reduce
It has been 1485 days since the last update, the content of the article may be outdated.
高阶函数
一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
javascript
function add(x, y, f) { |
map
由于map()方法定义在JavaScript的Array中,我们调用Array的map()方法,传入我们自己的函数,就得到了一个新的Array作为结果:
javascript
var arr=[1,2,3,4,5,6]; |
for python
python
def f(x): |
f()可以是任意函数,比如,把Array的所有数字转为字符串:
javascript
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; |
reduce
Array的reduce()把一个函数作用在这个Array的[x1, x2, x3…]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:
javascript
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4) |
数列求和:
javascript
function f(x,y){ |
for python
python
def f(x,y): |
利用reduce()求积:
javascript
; |
利用map和reduce操作实现一个string2int()函数:
javascript
; |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment