forEach在项目中的使用
forEach 会改变原始数组 被forEach循环的数组不能够为空
forEach会改变原始数组 value是内容 index是索引 array是你写的数组。
foeEach内部是异步的哈
功能描述: eachArr给数组的每一项 添加一个新的key值
为什么在项目中会使用foeach.因为forEach会改变原始数组。
我们在一些时候,就需要去使用原始数组。
比如:后端在给我们的每一项中只有3个字段。我们需要再添加一个字段去控制其他的。此时我们就可以去使用foreach。
eachArr: [
{ name: "lj", age: 20 },
{ name: "lh", age: 23 },
{ name: "yj", age: 21 },
]
giveEach() {
if (this.eachArr) {
this.eachArr.forEach((v, i, arr) => {
//添加一个新的key
this.eachArr[i]['url'] = "http";
})
console.log('123', this.eachArr)
}
},

forEach没有返回值
let arr=[
{name:'张三',age:13},
{name:'张三',age:13},
{name:'张三',age:13}
]
let newRrr=arr.forEach((item,index,arr)=>{
console.log( "每一项",item)
console.log( "索引",index)
console.log( "被循环的数组",arr)
return index
})
//因为forEach是没有返回值的,所以该值是 undefined
console.log("newRrr",newRrr );
不要在forEach中去执行异步任务
function delay(item){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(item)
},2000)
})
}
function fn(arr){
arr.forEach(async element => {
console.log( await delay(element) );
});
console.log('打印完毕' )
}
fn([1,2,3,4])
我们本来希望的是:
每个2s后,依次打印出1,2,3,4 然后最打印出【打印完毕】
但是实际却是:
先打印出==》打印完毕==》1,2,3,4一起被打印出来==》并没有每隔2s
怎么解决了,使用for of就ok了
function delay(item){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve(item)
},2000)
})
}
async function fn(arr){
for (const iterator of arr) {
console.log( await delay(iterator) );
}
console.log('打印完毕' )
}
forEach 中不支持 break 和 continue
null,undefined使用foeEach会报错,[]空数组不会.
遇见问题,这是你成长的机会,如果你能够解决,这就是收获。
作者:晚来南风晚相识
出处:https://www.cnblogs.com/IwishIcould/
本文版权归作者所有,欢迎转载,未经作者同意须保留此段声明,在文章页面明显位置给出原文连接
如果文中有什么错误,欢迎指出。以免更多的人被误导。
出处:https://www.cnblogs.com/IwishIcould/
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,或者关注博主,在此感谢!
万水千山总是情,打赏5毛买辣条行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主(っ•̀ω•́)っ✎⁾⁾!
想问问题,打赏了卑微的博主,求求你备注一下的扣扣或者微信;这样我好联系你;(っ•̀ω•́)っ✎⁾⁾!
支付宝
微信
如果文中有什么错误,欢迎指出。以免更多的人被误导。

浙公网安备 33010602011771号