map、forEach、filter和reduce方法比较

909 阅读4分钟

map、forEach、filter和reduce方法比较

在JS算法和Web前端开发中,map、forEach、filter是比较常用的对数组进行操作的方法,reduce则是比较少见的高阶函数。但由于它们语法相似,初学者在学习过程中经常会混淆这四者,对其概念和用法比较模糊。在总结过去学习成果时,我也顺便对这四个函数进行比较全面的对比分析。

语法

//map方法
array.map(function(currentValue,index,arr), thisValue)

//forEach方法
array.forEach(function(currentValue, index, arr), thisValue)

//filter方法
array.filter(function(currentValue,index,arr), thisValue)

//reduce方法
array.reduce(function(total, Value, index, arr), initialValue)
参数说明
必须参数描述可选参数描述
currentValue当前元素的值thisValue对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined"
index当前元素的索引值initialValue传递给函数的初始值(total)
arr当前元素属于的数组对象
total初始值, 或者计算结束后的返回值。

1、map函数

1-1、定义和用法

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。 map() 方法按照原始数组元素顺序依次处理元素。

1-2、方法特性

是否对空数组进行检测:否
是否能改变原始数组:否
是否返回数据:是
返回数组长度能否改变:否

1-3、用例

1-3-1、构造数组

[...Array(10000).keys()].map((v, i) => i + 1);

1-3-2、数组元素值翻倍

const double = numbers.map(function (num) {
    return num * 2;
})

1-3-3、获取列表里的object信息

const msg = error.details.map(el => el.message).join(',')

1-3-4、构造对象数组

newCamp.images = req.files.map(f => ({ url: f.path, filename: f.filename }))

2、forEach函数

2-1、定义和用法

forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。

2-2、方法特性

是否对空数组进行检测:否
是否能改变原始数组:是
是否返回数据:否

2-3、用例

2-3-1、遍历输出

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

function print(element) {
    console.log(element);
}
numbers.forEach(print)

2-3-2、计算数组所有元素相加的总和

<button onclick="numbers.forEach(myFunction)">点我</button>
<p>数组元素总和:<span id="demo"></span></p> 
<script> 
var sum = 0; 
var numbers = [65, 44, 12, 4]; 
function myFunction(item) { 
    sum += item; 
    demo.innerHTML = sum; 
} 
</script>

3、filter函数

3-1、定义和用法

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

3-2、方法特性

是否对空数组进行检测:否
是否能改变原始数组:否
是否返回数据:是
返回数组长度能否改变:是

3-3、用例

3-3-1、筛选数组

var ages = [32, 33, 16, 40];
function checkAdult(age) {
    return age >= 18;
}
document.getElementById("demo").innerHTML = ages.filter(checkAdult);}

3-3-2、筛选数组(反向筛选)

comments = comments.filter(c => c.id != id);

3-3-3、filter与map方法结合的链式操作

const movies = [
    {
        title: 'Amadeus',
        score: 99
    },
    {
        title: 'Stand By Me',
        score: 85
    },
    {
        title: 'Parasite',
        score: 95
    },
    {
        title: 'Alien',
        score: 90
    }
]
const goodMovies = movies.filter(m => m.score > 80)
const goodTitles = goodMovies.map(m => m.title)

movies.filter(m => m.score > 80).map(m => m.title);

4、reduce函数

4-1、定义和用法

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。 reduce() 可以作为一个高阶函数,用于函数的 compose。

4-2、方法特性

reduce() 是数组的归并方法,与forEach()、map()、filter()等迭代方法一样都会对数组每一项进行遍历,但是reduce() 可同时将前面数组项遍历产生的结果与当前遍历项进行运算,这一点是其他迭代方法无法企及的

是否对空数组进行检测:否
是否能改变原始数组:否
是否返回数据:是
返回数组长度能否改变:是

4-3、用例

4-3-1、数组元素累加

const prices = [9.99, 1.50, 19.99, 49.99, 30.50];
const total = prices.reduce((total, price) => {
    return total + price
})

4-3-2、条件筛选

const prices = [9.99, 1.50, 19.99, 49.99, 30.50];
const minPrice = prices.reduce((min, price) => {
    if (price < min) {
        return price;
    }
    return min;
})

4-3-3、求数组项最大值

var arr = [3,9,4,3,6,0,9];
var max = arr.reduce(function (prev, cur) {
    return Math.max(prev,cur);
});

4-3-4、扁平一个二维数组

var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
var res = arr.reduce((x, y) => x.concat(y), []);

5、参考资料

reduce() 方法
filter() 方法
forEach() 方法
map() 方法
颠覆者——JS中reduce() 的用法