【JS】数组forEach

微信订阅号: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}`);
})
微信订阅号: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()。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容