共同点
- 都只能循环
数组
- 都循环数组中的每一项
- 每次循环的
匿名函数
都有三个参数- 数组中的当前每一项
item
- 当前项的索引号
index
- 原数组
arr
- 数组中的当前每一项
- 匿名函数中的
this
指向window
例如:
let arr = ['hi','hello','hei'];
arr.forEach((item,index,arrays) => {
// item为每一项 , index为每项的索引号, arrays为原数组
console.log(item,index,arrays)
})
区别
.forEach()
没有返回值,改变元数组.map()
,有返回值, 返回新的数组,原数组不变
例如:
使用 forEach()
对数组进行返回
let arr = ['hi','hello','hei'];
let result = arr.forEach((item,index,arrays) => {
// item为每一项 , index为每项的索引号, arrays为原数组
console.log(item,index,arrays)
return 'hello world'
})
console.log(result)
返回结果如下:
使用 .map()
对数组进行返回
let arr = ['hi','hello','hei'];
let result = arr.map((item,index,arrays) => {
// item为每一项 , index为每项的索引号, arrays为原数组
console.log(item,index,arrays)
return 'hello world'
})
console.log(result)
返回结果如下:
用途
.forEach()
不改变数据,只是用数据做一些事情.map()
,需要返回一个新数组