微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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}
]

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,4 然后最打印出【打印完毕】
但是实际却是:
先打印出==》打印完毕==》1,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会报错,[]空数组不会.{注意}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐