js中的循环用法

一. for循环

for循环是根据数组的长度去确定循环次数的,而对象是没有长度这个属性的,所以,for循环不能用来遍历对象,可以用来遍历数组和字符串。

var arr = ['a', 'b', 'c']
for (let index = 0; index < arr.length; index++){
  console.log(arr[index])
}

二. for...in

for...in循环也是JS常用的循环方式,可以用来遍历数组、对象、字符串,特别适合遍历对象,用于遍历属性的键名。

var arr = ['a', 'b', 'c']
for (index in arr){
  console.log(arr[index]) //分别输出a b c
}

var obj = {name: "chen", age: 20}
for (x in obj){
  console.log(obj[x]) //分别输出chen, 20
}

三. for...of循环

for...of循环直接用来遍历属性值,不是遍历键名和下标。 可用于数组,不能用于对象

var arr = ['a', 'b', 'c']
for (const key of arr) {
  console.log(key)  //分别输出a,b,c
}

四. forEach(function) 只能用于数组

var array = ['a', 'b', 'c'];

array.forEach(function(element,index, arr) {
  console.log(element);
  console.log(index)
  console.log(arr)
});

或者使用箭头函数  https://blog.csdn.net/weixin_45112114/article/details/123358639
arr.forEach((item, index)=>{
  console.log(item)
})

箭头函数的简单用法:(参数) => { 函数体 }

forEach方法中的function回调有三个参数:
第一个参数是遍历的数组内容,
第二个参数是对应的数组索引,
第三个参数是数组本身

用在mongo中循环查询的一个简单例子

db = db.getSiblingDB("dn_pp");
models=db.devices.aggregate({$group: {_id: '$model'}})
models.forEach(function(model){
        print(model._id)
})

五. 遍历对象,除了for...in外,还有一种方法

var obj = {name: "chen", age: 20}

//遍历键名,输出键名组成的数组
console.log(Object.keys(obj));
//遍历键值,输出键值组成的数组
console.log(Object.values(obj));
posted @ 2022-11-14 15:53  坚强的小蚂蚁  阅读(158)  评论(0编辑  收藏  举报