map和foreach的用法和区别 |
您所在的位置:网站首页 › split改变原数组吗 › map和foreach的用法和区别 |
foreach和map的不同点: (1)map()方法会得到一个新的数组并返回,forEach()会修改原来的数组。 map遍历的后的数组通常都是生成一个新的数组,新的数组的值发生变化,当前遍历的数组值不会变化。 (2)forEach()允许callback更改原始数组的元素。map()返回新的数组。 forEach遍历通常都是直接引入当前遍历数组的内存地址,生成的数组的值发生变化,当前遍历的数组对应的值也会发生变化。 map类似下面 var arr = [1,2,3,4,5,6]; var new2Arr = arr.map((item,index,array) =>{ console.log(item); console.log(index); console.log(array); return item *100 }) console.log(arr); //[1, 2, 3, 4, 5, 6] console.log(new2Arr); // [100, 200, 300, 400, 500, 600] if (spuImageResult.code == 200) { let listArr = spuImageResult.data; listArr.forEach((item) => { //由于照片墙显示图片的数据需要数组,数组里面的元素需要有name与url字段 //需要把服务器返回的数据进行修改 item.name = item.imgName; item.url = item.imgUrl; }); // 数组进行变更或者替换时,name url这种新增的属性是可以监测到的。 this.spuImageList = listArr; console.log(JSON.parse(JSON.stringify(spuImageResult.data)),'---') console.log(JSON.parse(JSON.stringify(listArr)),'listArr') }foreach使用时,主要改变了原数组。从下图看,原来的数和新数一样 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |