forEach()与map()都是ECMAScript5中遍历的数组方法,它们在实际开发中会大量用到;那它们到底有着怎样的区别呢?一起来来看吧!
一.forEach()
forEach() 通过数组中的元素进行遍历迭代;对数组中的每个元素调用一次提供的回调函数.
该回调函数接受三个参数:
- 元素的值
- 元素索引
- 数组对象本身
let arr = [3, 6, 8, 9];
let res = arr.forEach((item, index) => {
return arr[index] = item * 2;
});
console.log(res); // undefined 注意:返回值是undefined
console.log(arr); // [6, 12, 16, 18] 注意:这里的原数组已经发生改变
二.map()
map() 依次为数组中的每个元素调用提供的回调函数,然后从结果中构造一个新数组.
该回调函数接受三个参数:
- 元素的值
- 元素索引
- 数组对象本身
let arr = [1, 3, 6];
let res = arr.map((item) => {
return item * 3;
});
console.log(res); // [3, 9, 18]
console.log(arr); // [1, 3, 6] 注意:原数组未发生改变
三.它们的区别
主要区别:
- forEach()会更改原始数组,而map()返回一个新数组,不更改原始数组
- 两个方法没有哪个更好,具体场景取决于你实际的开发环境