数组的几种遍历方法

237 阅读2分钟
数据map遍历:

语法:array.map(function(currentValue,index,arr), thisValue)
作用:映射数组(将数组每一个元素处理之后,得到一个新数组)
2.语法特点 :
2.1 循环执行次数 == 数组长度
2.2 回调函数内部return作用
(1)return 新元素值
(2)没有return,新元素都是undefined
2.3 map本身返回值作用
隐射之后的新数组

let arr = [20, 66, 80, 90, 100]
//完整写法
// let res = arr.map( (item,index)=>{
// return item*0.8
// })

//简写
let res = arr.map(item => item * 0.8)
console.log(res)

image.png

数组filter遍历:
array.filter(function(currentValue,index,arr), thisValue)

作用:筛选数组
2.语法特点 :
2.1 循环执行次数 == 数组长度
2.2 回调函数内部return作用
(1)return true : 满足筛选条件,当前元素放入新数组中
(2)return false : 不满足筛选条件,当前元素不放入新数组中
2.3 map本身返回值作用
筛选之后的新数组

        let arr = [20, 61, 80, 95, 100]
        //需求:筛选出数组中的偶数
        //完整写法
        // let res = arr.filter((item, index) => {
        //     console.log(item, index)
        //     if(item % 2 == 0){
        //         return true
        //     }
        // })
        //简洁写法
        let res = arr.filter(item => item % 2 == 0)
        console.log(res)

image.png

数组forEach遍历
array.forEach(function(currentValue, index, arr), thisValue)

作用:用于调用数组的每个元素,并将元素传递给回调函数。类似于for循环
2.语法特点 :
2.1 循环执行次数 == 数组长度
2.2 回调函数内部return作用

2.3 forEach本身返回值作用

        let arr = [20, 61, 80, 95, 100]
        arr.forEach((item, index) => {
            console.log(item, index)
        })

image.png

数组some遍历
array.some(function(currentValue,index,arr),thisValue)

作用:检测数组中的元素是否满足指定条件
2.语法特点 :
2.1 循环执行次数 != 数组长度
2.2 回调函数内部return作用
(1)return true : 循环结束。 找到满足条件的元素,此时some的返回值也是true
(2)return false : 循环继续。没有找到满足条件的元素,如果循环执行完毕还是false,最终some的返回值也是false
2.3 some本身返回值作用
return true : 有满足条件的元素
return false : 没有满足条件的元素

        let arr = [20, 61, 80, 95, 100]
        //需求:判断数组中有没有负数
        //完整写法
        let res = arr.some((item, index) => {
            if( item < 0 ){
                return true
            }
        })
        //简洁写法
        // let res = arr.filter(item=>item % 2 == 0)
        console.log( res )

image.png

数组every遍历
array.every(function(currentValue,index,arr), thisValue)

作用:数组所有元素是否都符合指定条件
2.语法特点 :
2.1 循环执行次数 != 数组长度
2.2 回调函数内部return作用
(1)return true : 循环继续。 当前元素满足条件,继续判断. 如果循环执行完毕还是true,则every返回值就是true
(2)return false : 循环结束。当前元素不满足条件。 every的返回值也是false
2.3 every本身返回值作用
return true : 全部元素都满足条件
return false : 有元素不满足

//需求:判断数组中有没有负数
        let arr = [20, 61, -80, 95, 100]
        //完整写法
        // let res = arr.every((item, index) => {
        //     if(item>0){
        //         return true
        //     }
        // })
        //简洁写法
        let res = arr.every(item => item > 0)
        console.log(res)

image.png