【JS】数组forEach

作者: 德育处主任 | 来源:发表于2019-01-30 23:11 被阅读1次
微信订阅号: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()。

相关文章

  • js 中的 forEach 和 jQuery 中的 each

    js 中的 forEach 方法: 用法:数组.forEach(function) EcmaScript 5 中的...

  • forEach 浅析

    今天聊聊forEach; 首先看看foreach的用法: 1. 原生JS的forEach: 参数:value数组中...

  • $.each()与forEach()的区别,伪数组是什么

    $.each()是jq中的方法,forEach()是js方法1、$.each()可以遍历伪数组;forEach()...

  • forEach和each

    forEach forEach是js中遍历数组的方法 forEach有3个参数,第一个参数表示遍历的数组内容,第二...

  • 数组(Array)<迭代器>

    一、Js数组迭代器方法 主要介绍js数组中的forEach,every,some,filter,map迭代器方法 ...

  • 【JS】数组forEach

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

  • 数组

    forEach(js v1.6) map()— —更新数组 filter()、includes()、find()、...

  • 关于JS中的循环

    JS 中的循环有for...in, for..of, forEach forEach遍历数组的时候是无法通过bre...

  • for循环性能比较

    JS数组遍历的几种方式 JS数组遍历,基本就是for,forin,foreach,forof,map等等一些方法,...

  • JS遍历相关知识

    JS数组遍历的几种方式 JS数组遍历,基本就是for,forin,foreach,forof,map等等一些方法,...

网友评论

    本文标题:【JS】数组forEach

    本文链接:https://www.haomeiwen.com/subject/cgyhsqtx.html