- 相同点:
-
遍历数组的每一项
-
都需要一个回调函数,且都支持三个参数:item(当前每一项),index(索引值),arr(原数组)
-
匿名函数中的this都指向window
-
不同点
- forEach 遍历后没有返回值,且不能直接修改原数组,如果数组的元素是对象,可以修改对象的属性
let list = [ { name: 'a', age: 1 }, { name: 'b', age: 3 }, ];
list.forEach((item, index, arr) => {
arr[index].name = 'c';
});
console.log(list);
// [{"name":"c","age":1},{"name":"c","age":3}]
2.map会返回一个新数组,原数组没有变化,