整理了一些数组遍历的方式
1. for循环
1 | //最简单的一种循环遍历方式,也是使用频率最高的 |
2.for in(对象遍历)
1 | for(let key in obj){ |
3. for of (不能循环对象)
1 | for(let val of arr){ |
4.ES6 中的 forEach( ) 数组元素有几个,该方法的回调就会执行几次
1 | arr.forEach((item,index,arr)=>{ |
1 | const array1 = ['a', 'b', 'c']; |
5.map映射一个数组或者对象,也可以遍历json对象
1 | const array1 = [1, 4, 9, 16]; |
6.filter 过滤遍历数组,过滤出符合条件的元素并返回一个新数组
1 | const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; |
7.some 遍历数组,只要有一个以上的元素满足条件 就返回true ,否则返回 false
1 | const array = [1, 2, 3, 4, 5]; |
8.every 遍历数组,每一个元素都满足条件 则返回 true 否则返回 false
1 | let somebool = datalsit.some((item,index)=>{ |
9.find ES6 遍历数组,返回符合条件的第一个元素,如果没有符合条件的元素则返回 undefined
1 | let arr1 = [1,2,3,4,5,6,7] |
10.findIndex ES6遍历数组,返回符合条件的一个元素的索引,如果没有符合条件的元素则返回-1
1 | let arr2 = [1,2,3,5,7,8,2,4,5]; |