foreach 和 map的区别

javascript使用(foreach 和 map的区别)

举例说明:
假设有一个对象:

var obj = [
    {
        id:1,
        text:"hello"
    },
    {
        id:2,
        text:"world"
    },
    {
        id:3,
        text:"!!!"
    }
];
  1. 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: '!!!' }
  1. 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必须有返回值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值