js中Array对象的常用遍历方法详解

编程学习 2021-07-04 15:50www.dzhlxh.cn编程入门
今天长沙网络推广就为大家分享一篇关于js中Array对象的常用遍历方法详解,长沙网络推广觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随长沙网络推广来看看吧

1.forEach(),遍历数组的每个元素

  let arrFor = ['muzi','digbig','muzidigbig','lucky']
  //forEach(),遍历数组的每个元素
  arrFor.forEach((item,index) => {
    console.log(`${index}---${item}`)
  })

2.map(参数为回调函数)函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新数组,原数组不变;

  let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
  const arrMap = arr.map((item,index) => {
    return {
      id:item.id,
      name:item.name,
      sex:'男'
    }
  })
  console.log(arrMap)

3.filter(参数为回调函数)函数:过滤通过条件的元素组成一个新数组,原数组不变;

  let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
  const arrFilter = arr.filter((item,index) => {
    return item.id >= 2;
  })
  console.log(arrFilter)

4.some(参数为回调函数)函数,遍历数组中是否有符合条件的函数,返回布尔值;

  let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
  const arrSome = arr.some((item,index) => {
    return item.id === 5
  })
  console.log(arrSome)

5.every(参数为回调函数)函数,遍历数组是否每个元素都符合条件,返回布尔值;

  let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
  const arrEvery = arr.every((item,index) => {
    return item.id >= 1
  })
  console.log(arrEvery)

6.find()函数,数组中的每个元素都执行这个回调函数;返回第一个满足条件的元素 之后的元素就不在调用;没有符合的返回undefined;并没有改变数组的原始值。

  let arr = [{id:1,name:'muzi'},{id:2,name:'digbig'},{id:3,name:'muzidigbig'},{id:4,name:'lucky'}]
  const arrFind = arr.find((item,index) => {
    return item.id === 1
  })
  console.log(arrFind)

7.reduce(),合并二维数组

  var twoArr = [['mu','zi'],['dig','big'],['lucky','jiji']];
  var oneArr = twoArr.reduce(function(total,currentValue){
    // console.log(total)
    return total.concat(currentValue);
  },[])
  console.log(oneArr);//["mu", "zi", "dig", "big", "lucky", "jiji"]

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对狼蚁SEO的支持。如果你想了解更多相关内容请查看狼蚁网站SEO优化相关链接

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板