【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 跳过循环中的一个迭代,跳过之后会执行下一个迭代。


扫描二维码关注公众号,回复: 5189890 查看本文章

【跳过一次迭代】

/* 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()。

猜你喜欢

转载自blog.csdn.net/weixin_34232617/article/details/87134755