js遍历数组的几种方法

不想你离开。 提交于 2019-11-29 17:09:19

第一种:for循环,也是最常见的

const arr = [11,22,33,44,55,66,77,88]
for (let i = 0; i < arr.length; i++) {
            console.log(arr[i])
        }

 

 

第二种:forEach()

 1)、forEach()遍历普通数组

arr.forEach( function(item){
            console.log(item)
        } )

 2)、forEach()遍历对象类型数组

const arr = [
            {id:1,name:'zhangsan'},
            {id:2,name:'lisi'},
            {id:3,name:'wangwu'}
        ]

arr.forEach( function(item){
            console.log(item.id + '---' +  item.name)
        })

输出结果:

 

第三种: map()方法

map即是 “映射”的意思 ,原数组被“映射”成对应新数组

var newArr = arr.map( function(value,index){
    console.log(value + '---' + index)
    return value + 10
})

console.log(newArr)

输出结果:

注意:forEach()和map()区别:

1、forEach:用来遍历数组中的每一项,这个方法执行没有返回值,不影响原数组

2、map:支持return,相当与原数组克隆了一份,把克隆的每项改变了,也不影响原数组

 

第四种: for....in   方法

for....in 是es5标准, 此方法遍历数组效率低,主要是用来循环遍历对象的属性

1)、 for......in  遍历数组

for(let item in arr){
            console.log(arr[item])
        }

 

2)、for.....in 遍历对象

循环遍历对象的属性,js中动态获取key,得到某对象中相对应的value = obj[key]

const obj = {
            a:1,
            b:2,
            c:3
        }

for(let key in obj){
            console.log(key + '---' + obj[key] )
        }

输出结果:

 

第五种: for.......of    方法    (es6支持)

for(let item of arr){
            console.log(item)
        }

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!