前言
编码过程中一直分不清map和forEach的区别,闲下来,弄几个例子研究一下。
一、map
1.简单数组
const a = [ 5, 7, 10, ]
const mapA = a.map((item, index, arr) => {
console.log(item, index, arr)
return item * 2
})
console.log(mapA)
输出:
2.对象数组
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
const mapC = c.map((item, index, arr) => {
console.log(item, index, arr)
let res = this.$deepCopy(item)
res.value += index
return res
})
console.log(c)
console.log(mapC)
输出:
所以事实上map不仅可以遍历数组,还可以返回一个新数组。
3.修改简单数组内容
const a = [ 5, 7, 10, ]
const mapA = a.map((item, index, arr) => {
console.log(item, index, arr)
arr[index] = item * 2
return item * 2
})
console.log(a)
console.log(mapA)
输出:
4.修改对象数组内容
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
const mapC = c.map((item, index, arr) => {
console.log(item, index, arr)
let res = item
res.value += index
return res
})
console.log(c)
console.log(mapC)
输出:
可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组
map的其他用法详见文档
二、forEach
1.简单数组
const a = [ 5, 7, 10, ]
a.forEach((item, index, arr) => {
arr[index] = item * 2
console.log(item, index, arr)
})
console.log(a)
输出:
2.对象数组
const c = [
{
key: 'key1',
value: 'value1',
},
{
key: 'key2',
value: 'value2',
},
]
c.forEach((item, index, arr) => {
console.log(item, index, arr)
item.value += index
})
console.log(c)
输出:
可见,对象数组在遍历的过程中,修改属性的值就可以影响到原数组