forEach()数组遍历


forEach() 方法对数组的每个元素执行一次给定的函数。只对数组有效

特性

forEach()本身不返回有意义的值,return会返回undefined

语法:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

参数:

arr.forEach有三个参数,分别是:

1、arr:被遍历的数组

2、callback(currentValue,index,array){句柄}:回调函数,该回调函数接受三个参数:

  A、currentValue:遍历到的当前元素

  B、index:为currentValue的索引

  C、array:被遍历的数组

3、thisArg:指代遍历中this的值

示例:

    let arr = [1, 2,3]
    let newArr=arr.forEach(function (currentValue, index, ar) {
        console.log(currentValue);//遍历打印1,2,3
        console.log(index);//遍历打印0,1,2
        console.log(ar);//遍历打印三次[1, 2, 3]
        console.log(this)//String {"我就是this的值"};遍历打印三次
        return ar[index]= currentValue * 2
      }, "我就是this的值")
      //输出
      console.log(arr);//[2, 4, 6]        改变了原来的数组
      console.log(newArr);//undefined     返回undefined

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM