js中常用的遍历函数

来源:互联网 发布:酷q机器人php源码 编辑:程序博客网 时间:2024/06/01 08:53
  1. for循环,需要知道数组的长度,才能遍历,
let arr =['2','test',true,'HelloWorld'];        for (let i = 0; i < arr.length; i++) {            console.log(arr[i]);        }

这里写图片描述
2. forEach循环,循环数组中每一个元素并采取操作, 没有返回值, 可以不用知道数组长度

let arr =['2','小明',true,'HelloWorld'];        arr.forEach((i,index)=>{            i='hi,'+i;            console.log(i);        })

这里写图片描述
3. map函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新的数组,原数组不变

let arr =['2','小明',true,'HelloWorld'];        var newstate=arr.map(function(index) {            index="map的"+index;            console.log(index)            return index;        })        console.log("newstate", newstate);

这里写图片描述
4. filter函数, 过滤通过条件的元素组成一个新数组, 原数组不变

let arr =['2',3,'小明',true,'HelloWorld'];        var newstate=arr.filter(function(index) {            return typeof index==='number';        })            console.log(arr,newstate)

    这里写图片描述 
 5. some函数,遍历数组中是否有符合条件的元素,返回Boolean值

let arr =['2',3,'小明',true,'HelloWorld'];        var newstate=arr.some(function(index) {            return typeof index==='number';        })            console.log(arr,newstate);

   这里写图片描述   

  1. every函数, 遍历数组中是否每个元素都符合条件, 返回Boolean值
let arr =['2',3,'小明',true,'HelloWorld'];        var newstate=arr.every(function(index) {            return typeof index==='number';        })            console.log(arr,newstate);

这里写图片描述

当然, 除了遍历数组之外,还有遍历对象,常用方法 in

let obj ={a:'2',b:3,c:true};        for (var i in obj) {            console.log(obj[i],i)        }            console.log(obj);

   这里写图片描述 

in 不仅可以用来 遍历对象,还可以用来遍历数组, 不过 i 对应与数组的 key值

     这里写图片描述