1.map
map一般来说针对数组进行操作。map函数以函数作为参数,这个函数参数作用在数组的每一个元素上。
举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个数组[1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map实现如下:

代码如下:
<script>
let pow=(x)=>x*x;
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);
</script>
运行结果:
(9) [1, 4, 9, 16, 25, 36, 49, 64, 81]
map函数里也可以传入匿名函数,比如:
<script>
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]
</script>
运行结果:
(4) [8, 6, 7, 9]
2.reduce
reduce函数是将数组的前两个元素做运算,将运算的结果再与第三个元素做运算,以此类推运算到最后一个元素得出最后的结果。
reduce规定必须接受两个参数。reduce()把结果继续和序列的下一个元素做累计计算。
比如,对数组进行求和,就可以使用reduce.
<script>
const arr = [1, 3, 5, 7, 9];
let result = arr.reduce(function (x, y) {
return x + y;
});
console.log("sum="+result);
</script>
运行结果:
sum=25