关于这两个原生 API 相关的
区别/使用,语言尽量通俗易懂,减少废话,如果想了解更深层次,去看隔壁看的博客/文档,或许会更好
简单来说:
- 都是用来
遍历数组/映射 - 会对每个
会对每个数组元素依次进行操作 forEach()没有返回值,会改变原数组map()有返回值,不会改变原数组
forEach()
遍历数组,并且对每个 item 依次执行相对应的方法,没有返回值
forEach() 接受一个函数,该函数传入 3 个参数:数组元素 数组下标(可选) 数组本身(可选),咱把这些东西 log 出来:
let arr = [1, 2, 3]
arr.forEach((item, index, arrObj) => {
console.log(`item: ${item}, index: ${index}, arrObj: ${arrObj}`)
})
// item: 1, index: 0, arrObj: 1,2,3
// item: 2, index: 1, arrObj: 1,2,3
// item: 3, index: 2, arrObj: 1,2,3
forEach() 没有返回值,会改变原数组 (不做演示了)
var arr = [1, 2, 3]
let newArr = arr.forEach((item, index, arrObj) => {
return arr
})
console.log(newArr)
// undefined
map()
遍历数组,并且对每个 item 依次执行对应的方法,与 forEach 不同的是,map 会把每一次执行的结果变成一个新数组返回
map() 接受一个函数,该函数传入 3 个参数:数组元素 数组下标(可选) 数组本身(可选),咱把这些东西 log 出来:
let arr = [1, 2, 3]
arr.map((item, index, arrObj) => {
console.log(`item: ${item}, index: ${index}, arrObj: ${arrObj}`)
})
// item: 1, index: 0, arrObj: 1,2,3
// item: 2, index: 1, arrObj: 1,2,3
// item: 3, index: 2, arrObj: 1,2,3
map() 有返回值,返回新数组,原数组不变
var arr = [1, 2, 3]
let newArr = arr.map((item, index, arrObj) => {
return item + 1
})
console.log(newArr)
// [ 2, 3, 4 ]
// [ 1, 2, 3 ]