JS 中几种常用的循环方式

作者: adm 分类: 前端 发布时间: 2023-06-04

1. 普通的for 循环

  遍历数组时 i 可设定 i 为下标 length 为循环次数 i++ 为循环下标的更新

    let list=[
      {name:'张三',age:22},
      {name:'李四',age:24},
      {name:'王五',age:18},
      {name:'小明',age:18},
      {name:'小红',age:18},
      {name:'小张',age:18}
    ]
    for(let i=0;i<list.length;i++){ 
      console.log(list[i])   // {name:'张三',age:22}   {name:'李四',age:24}  {name:'王五',age:18} 等等
    }

2. for in 循环

  遍历数组时 i 为下标 遍历对象时 i 为属性名

let list=[
  {name:'张三',age:22},
  {name:'李四',age:24},
  {name:'王五',age:18},
  {name:'小明',age:18},
  {name:'小红',age:18},
  {name:'小张',age:18}
]
for(let i in list){    //遍历数组或JSON时 i 为下标
  console.log(list[i]) // {name:'张三',age:22}   {name:'李四',age:24}  {name:'王五',age:18} 等等
}
let obj={name:'张三',age:22} 
for(let i in obj){     // 遍历对象时  i 为属性名
  console.log(obj[i],i)   //张三,name   22,'age'
}

3. for of 循环

  遍历数组时 i 为当前的值 不可遍历普通对象

let list=[
  {name:'张三',age:22},
  {name:'李四',age:24},
  {name:'王五',age:18},
  {name:'小明',age:18},
  {name:'小红',age:18},
  {name:'小张',age:18}
]
let list2=[1,2,3,4,5,6]
let obj={name:'张三',age:22} 
for(let i of list){
  console.log(i)     //{name: '张三', age: 22}  {name: '李四', age: 24}   {name: '王五', age: 18} 等等
}
for(let i of list2){
  console.log(i)     //1 2 3 4 5 6
}
for(let i of obj){
  console.log(i)     //报错 obj is not iterable   es6中的“for of”不能遍历对象   原因请看 Iterator接口
}

4.forEach 循环

 forEach方法用于调用数组中的每个元素,并将(元素val 下标index 原数据arr)传递给回调函数。

let list=[
  {name:'张三',age:22},
  {name:'李四',age:24},
  {name:'王五',age:18},
  {name:'小明',age:18},
  {name:'小红',age:18},
  {name:'小张',age:18}
]
list.forEach((val,index,arr)=>{
  console.log(val,index,arr)   //{name: '张三', age: 22}第一条数据  0下标   arr 原数组  {name: '李四', age: 24}第二条数据  1下标   arr 原数组   等等
  val.age=val.age/2
})
console.log(list)    //{name: '张三', age: 11}{name: '李四', age: 12}{name: '王五', age: 9}{name: '小明', age: 9}{name: '小红', age: 9}{name: '小张', age: 9}

5.map循环

map() 方法返回一个新数组,数组中的元素为原始数组元素处理后的值。

let list=[
  {name:'张三',age:22},
  {name:'李四',age:24},
  {name:'王五',age:18},
  {name:'小明',age:18},
  {name:'小红',age:18},
  {name:'小张',age:18}
]
let newList=list.map((item,index,list)=>{
  item.name=`新${item.name}`
  item.age=item.age*2
  return item
})
console.log(newList,list)   //[{name: '新张三', age: 44},{name: '新李四', age: 48},...]   [{name: '张三', age: 22},{name: '李四', age: 24},...]  

map和forEach的区别

forEach() 方法不会返回执行结果,而是undefined。 map会返回一个新数组 也就是说 forEach会修改原来的数组。而map()方法会得到一个新的数组并返回

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!