亲宝软件园·资讯

展开

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

muzidigbig 人气:0

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

总结

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

加载全部内容

相关教程
猜你喜欢
用户评论