js-关于数组forEach方法的个人理解

JavaScript Array forEach() 方法

https://www.runoob.com/jsref/jsref-foreach.html

这是挂载在数组上的原型方法,用于遍历数组。

基础用法:

var numbers = [4, 9, 16, 25];
numbers.forEach(function(currentValue){
    console.log(currentValue) // 4, 9, 16, 25
    if(currentValue == 9) {
		currentValue = 10
	}
})
console.log(numbers) //[4, 10, 16, 25]

一个中规中矩的遍历数组方法。完整的api如下:

var numbers = [4, 9, 16, 25];
let thisValue = 1
 
numbers.forEach(function(currentValue, index, arr){
    console.log(currentValue,index,arr)
    console.log(thisValue)
    console.log(this)
}, thisValue)
// 4 0 [ 4, 9, 16, 25 ]
// 1
// [Number: 1]
// 9 1 [ 4, 9, 16, 25 ]
// 1
// [Number: 1]
// 16 2 [ 4, 9, 16, 25 ]
// 1
// [Number: 1]
// 25 3 [ 4, 9, 16, 25 ]
// 1
// [Number: 1]

遍历数组时可同时获得以下参数:

遍历项currentValue
遍历索引index
数组本身arr
this指向thisValue/this

本人能力有限,只能给大家先探路探到这里了。

如果有更漂亮的写法欢迎来讨论,让我们一起有条不紊的持续进步。
喜欢的话不妨点个小小的赞与关注,您的赞与关注将是我源源不断的前进动力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值