有个关于forEach 很奇怪的问题,第一次遇到,想请大家帮忙看看,谢谢?

作者站长头像
站长
· 阅读数 15
.then(res=>{
                    let data = res.data.data
                    this.fileList1 = data.memorandum_img
                    let price_url = this.price_url
                    this.fileList1.forEach(function(item){
                        item.url = price_url + item.url
                    })
                    console.log(this.fileList1,'this.fileList1111')
                    console.log(res,'res88')
                    
                })

我forEach this.fileList1 这个数组对象,给里面的一个item.url属性拼接了一个url字符串,console.log(this.fileList1,'this.fileList1111') 这个结果是我想要的,也是拼接后的数据

但是 console.log(res,'res88') 这里也变成了拼接后的数据,正常显示应该是没拼接的数据,当我把

this.fileList1.forEach(function(item){
                        item.url = price_url + item.url
                    })

注释后, console.log(res,'res88') 这时候打印才是没拼接的数据,

难道forEach 循环 改变属性值 ,还会影响res里的数据吗?我第一次遇到,请问这是什么原因?如何解决呢?

回复
1个回答
avatar
test
2024-07-17
  1. 将 forEach 替换为 map 方法,同时使用一个变量去接收 map 方法的结果
  2. 将 res.data.data 深克隆给 data 变量,而不是直接使用 = 去赋值
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容