欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-24 00:01:52
1.foreach(),遍历数组的每个元素 let arrfor = ['muzi','digbig','muzidigbig','lucky'] //...

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)

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

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)

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

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

总结

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