【JS】数组forEach

7275569-3ee72a16cb6cd62b.jpg
微信订阅号:Rabbit_svip

forEach()方法用于调用数组的每一个元素,并将元素传递给回调函数。

语法

array.forEach(function(currentValue, index, arr), thisValue)

  • currentValue:必填,当前元素。
  • index:可选,当前元素的索引。
  • arr:可选,当前元素所属的数组对象。
  • thisValue:可选,传递给函数的值一般用this值,如果这个参数为空,"undefined"会传递给"this"值。(这个参数一般很少填)
/* JS代码 */

let colors = ['red', 'blue', 'green'];

colors.forEach((item, $index, arr) => {
  console.log(`${item} => ${$index} => ${arr}`);
})
7275569-5b2dc7c59e2aa496.png
微信订阅号:Rabbit_svip

上面的代码用了ES6语法,几乎等同于下面的代码

/* JS代码 */

var colors = ['red', 'blue', 'green'];

colors.forEach(function(item, $index, arr) {
  console.log(item + ' => ' + $index + ' => ' + arr);
})




其实,用 forEach() 主要是为了更方便的代替 for 对数组进行遍历。

用 for 遍历数组的方法

/* JS代码 */

var colors = ['red', 'blue', 'green'];

for( var i=0; i < colors.length; i++){
  console.log( colors[i] + ' => ' + i + ' => ' + colors);
}

注意:

1、 forEach() 对于空数组是不会执行回调函数的。
2、 for可以用continue跳过循环中的一个迭代,forEach用continue会报错。
3、 forEach() 需要用 return 跳过循环中的一个迭代,跳过之后会执行下一个迭代。


【跳过一次迭代】
/* JS代码 */

var colors = ['red', 'blue', 'green'];

for( var i=0; i < colors.length; i++){
  if( colors[i] == 'blue') {
    continue;
  }
  console.log( colors[i] );
}

colors.forEach( function( item ) {
  if(item == 'blue') {
    return;
  }
  
  console.log( item );
})




注意:

没有办法终止或跳出forEach循环,除非抛出一个异常。

如果需要终止或者跳出循环,建议用some()或者every()。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值