javascript使用(foreach 和 map的区别)
举例说明:
假设有一个对象:
var obj = [
{
id:1,
text:"hello"
},
{
id:2,
text:"world"
},
{
id:3,
text:"!!!"
}
];
- foreach : 没有返回值
# 使用forEach:只能循环对obj数组进行处理
obj.forEach((item)=>{
/**
* @param {*item} 本次循环的值
* @param {*index} 本次循环的下标
* @param {*arr} 当前循环的对象
*/
console.log(item)
})
输出结果:————————————————————————————————————————————————————————————
{ id: 1, text: 'hello' }
{ id: 2, text: 'world' }
{ id: 3, text: '!!!' }
- map
(1)深拷贝
let newArr1 = obj.map((item,index,arr)=>{
if(item.id % 2 == 0){
item["test"] = true;
}
return item
})
console.log("newArr1 == " ,newArr1)
console.log("obj == ",obj)
输出结果:————————————————————————————————————————————————————————————
newArr1 == [
{ id: 1, text: 'hello' },
{ id: 2, text: 'world', test: false },
{ id: 3, text: '!!!' }
]
obj == [
{ id: 1, text: 'hello' },
{ id: 2, text: 'world', test: false },
{ id: 3, text: '!!!' }
]
直接在原数据上,对item进行赋值的话,会改变原数组的内容,即为深拷贝。
(2)浅拷贝
let newArr2 = obj.map((item,index,arr)=>{
const new_item = {...item} // 对item数组使用展开运算符“...” 来实现浅拷贝
if(new_item.id % 2 == 0){
new_item["test"] = false;
}
return new_item
})
console.log("newArr2 == " ,newArr2)
console.log("obj == ",obj)
输出结果:————————————————————————————————————————————————————————————
newArr2 == [
{ id: 1, text: 'hello' },
{ id: 2, text: 'world', test: false },
{ id: 3, text: '!!!' }
]
obj == [
{ id: 1, text: 'hello' },
{ id: 2, text: 'world' },
{ id: 3, text: '!!!' }
共性
二者都是处理循环,进行遍历处理。
差距
foreach 处理的是数组本身,没有返回值
map可以有返回值,但是还是需要区分深拷贝与浅拷贝。
常用的还有过滤器:filter
let newArr3 = obj.filter((item,index,arr) =>{
const test = item.id + 2;
if(test > 3){
return true;
}
else{
return false;
}
}
)
console.log("newArr3 ==",newArr3)
console.log("obj == ",obj)
输出结果:————————————————————————————————————————————————————————————
newArr3 == [ { id: 2, text: 'world' }, { id: 3, text: '!!!' } ]
obj == [
{ id: 1, text: 'hello' },
{ id: 2, text: 'world' },
{ id: 3, text: '!!!' }
]
filter 回调函数需要返回一个布尔值:
返回的为true 为存储到newArr3中,反之则不存储。
最终,filter 会返回一个新数组,包含所有回调函数返回 true 的元素。
因此,filter为一个过滤器。filter必须有返回值。