Web让前端飞网页前端后台技巧(CSS+HTML)

【JS】数组forEach

2019-01-30  本文已影响1人  德育处主任
微信订阅号:Rabbit_svip

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

语法

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

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

上一篇 下一篇

猜你喜欢

热点阅读