forEach、map、filter的区别
一、相同点
(1)都会循环遍历数组中的每一项
(2)map()、forEach()和filter()方法里每次执行匿名函数都支持3个参数
(3)只能遍历数组
二、不同点
(1)map()和filter()会返回一个新数组,不对原数组产生影响;
forEach()不会产生新数组,无返回值
1、Array.forEach()
介绍:
将数组循环一遍,函数参数有三个入参,不返回任何数据
格式:
[].forEach((item, index, arr) => {})
使用场景:
需要遍历一个数组的时候
示例:
const arr = ["张三", "李四", "王五"];
arr.forEach((item, index, arr) => {
console.log(item, index);
});
// '张三' 0
// '李四' 1
// '王五' 2
2、Array.filter()
介绍:
对数组进行筛选,接收一个方法作为参数,该方法的返回值为 true 时就将该元素添加进新的数组
格式:
[].filter((item, index, arr) => true)
返回值:
一个新的数组