一,ES5中数组遍历方式:
1.for 循环
**
for(let i = 0;i<arr.length;i++){
console.log(arr[i])
}
复制代码
2.forEach()遍历
**
arr.forEach((item=>{
console.log(item)
}))
复制代码
注意: forEach只做循环遍历(可在内部对数组元素执行操作),没有值返回
3.map() 映射数组,返回一个新的数组,数组中的每一个元素是原数组中的元素依次执行函数中的程序并返回的结果,不改变原数组
**
let arr = [1,2,3,4,5]
let result = arr.map(item=>item * 2)
console.log(result) // [2,4,6,8,10]
复制代码
4.filter() 遍历返回符合条件的元素组成的数组
**
let arr = [2, 4, 5, 12, 33, 6, 8]
let result = arr.filter(item=> item > 10)
console.log(result) // [12 , 33]
复制代码
5.reduce((acc ,item , index , arr) => {}, initValue) (很强大的方法~~~)
acc: 累加器 initValue:累加器的初始值
求和
**
let arr = [1 , 2 , 3 , 4]
let sum = arr.reduce((acc,item)=>{
return acc + item
},0) // 累加器的初始值可以根据需求的不同传递不同的值
console.log(sum) // 10
复制代码
5.some() 返回布尔值,判断是否有元素符合条件 只要有一个元素符合条件就返回true
**
let arr = [1, 3, 5, 7, 8, 11 , 14]
let bool = arr.some(item => item % 2 === 0)
console.log(bool) // true
复制代码
6.every()返回布尔值,只有每一个元素符合条件才能返回true 否则返回false
**
let arr = [1, 3, 5, 7, 8, 11 , 14]
let bool = arr.some(item => item % 2 === 0)
console.log(bool) // false
复制代码
二,ES6新增数组遍历方式:
1.find() 遍历数组并返回第一个符合条件的元素
**
let arr = [1, 3, 5, 7, 8, 11 , 14]
let res = arr.find(item=> item % 2 === 0)
console.log(res) // 8
复制代码
2.findIndex() 遍历数组并找到数组中第一个符合条件的值的索引
**
let arr = [1, 3, 5, 7, 8, 11 , 14]
let res = arr.findIndex(item=> item % 2 === 0)
console.log(res) // 4
复制代码
3.for of , values() , keys() , entries()使用
**
for(let item of arr){ //直接使用for of 等同于 values() 输出每一个元素的值
console.log(item) // 1 2 3 4 5 6 2 3
}
复制代码
values() 输出每一个元素的值
**
for(let item of arr.values()){
console.log(item) // 1 2 3 4 5 6 2 3
}
复制代码
keys() 输出每一个元素的索引
**
for(let item of arr.keys()){
console.log(item) //0 1 2 3 4 5 6 7
}
复制代码
entries() 输出每一个元素的索引与值
**
for(let [index,item] of arr.entries()){ //.entries( 输出每一个元素的索引与值
console.log('索引',index,‘值’,item)
}
//输出结果:
// 索引 0 值 1
//索引 1 值 2
//索引 2 值 3
//索引 3 值 4
//索引 4 值 5
//索引 5 值 6
//索引 6 值 2
//索引 7 值 3