Login
芋圆社区 > 编程 > JavaScript > forEach方法

forEach方法

1029
0
2022-03-10
2022-10-09
Hey、小怪兽

  • • forEach() 方法按升序为数组中含有效值的每一项执行一次 callback 函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上)
  • • 可依次向 callback 函数传入三个参数:
  • - 数组当前项的值
  • - 数组当前项的索引
  • - 数组对象本身
  • • 用6个例子理解forEach
  • - 例1(forEach() 方法对数组的每个元素执行一次提供的函数):
var array = ['a', 'b', 'c'];

array.forEach(function(el) {
    console.log(el);
});

array.forEach((el) => {
    console.log(el);
});

// 输出为:a,b,c
  • - 例2(forEach写成for):
var arr = [1,2,3,4];
arr.forEach(alert); 

// 等价于:
var arr = [1, 2, 3, 4];
for (var k = 0, length = arr.length; k < length; k++) {
    alert(arr[k]);
} 
  • - 例3(for写成forEach):
var arr = [2, 3, 7];

for(var i=0; i < arr.length; i++) {
    console.log('a['+i+'] = '+ arr[i]);
} 
// a[0] = 2
// a[1] = 3
// a[2] = 7

// 等价于:
arr.forEach(function(v, i){
    console.log('a['+i+'] = '+ v);
})
  • - 例4(三个参数的用法):
var arr = [1,2,3,4];
var sum = 0;

arr.forEach(function(value,index,array){
    array[index] === value; //结果为true
    sum += value; 
});

console.log(sum); //结果为 10
  • - 例5(如果数组在迭代时被修改了,则其他元素会被跳过,下面的例子会输出 "one", "two", "four"。当到达包含值 "two" 的项时,整个数组的第一个项被移除了,这导致所有剩下的项上移一个位置。因为元素 "four" 正位于在数组更前的位置,所以 "three" 会被跳过。 forEach() 不会在迭代之前创建数组的副本): 
var words = ['one', 'two', 'three', 'four'];
words.forEach(function(word) {
  console.log(word);
  if (word === 'two') {
    words.shift();
  }
});

// one
// two
// four
  • - 例6(扁平化数组):
function flatten(arr) {
  const result = [];

  arr.forEach((i) => {
    if (Array.isArray(i))
      result.push(...flatten(i));
    else
      result.push(i);
  })

  return result;
}

// Usage
const problem = [1, 2, 3, [4, 5, [6, 7], 8, 9]];

flatten(problem); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • • forEach无法通过return来中止循环,return只能跳出当前循环,进入下一次循环:
  • // 输出12456,3不会输出
    [1,2,3,4,5,6].forEach((n) => {
    	if (n=== 3) {
    		return
    	}
        console.log(n)
    })
  • • 抛出异常可以中止forEach循环
  • // 输出12,3456不会输出
    try{
        [1,2,3,4,5,6].forEach((n) => {
            if (n=== 3) {
                throw new Error('End Loop')
            }
            console.log(n)
        })
    } catch (e) {}

上一篇:批量命名全局变量

下一篇:round,ceil,floor

Message Board
回复
回复内容不允许为空
留言字数要大于2,小于200!
提交成功,5s后刷新页面!
编程导航

Array 基础方法

Array 进阶方法 - ES6

公主连结.cysp转.skel

获取视频的第一帧

定制Console.log

WebAssembly简单案例

一些常用的方法【持续更新】

AES加密 CBC模式

滚动条滚动到底部的判断

console.log展开值不一样

JSON解析与序列化

|| 运算符的坑

对象转为字符串

call,apply,bind

获取数组中对象的某一属性值

jQuery合并ajax请求

批量命名全局变量

forEach方法

round,ceil,floor

Copyright © 2020 芋圆社区

Powered by 浙ICP备2020039309号-1

此页面不支持夜间模式!

已进入夜间模式!

已进入普通模式!

搜索框不允许为空

签到成功!经验+5!芋圆币+2!

签到失败!今日已签到!

需要登录社区账号才可以进入!

复制成功
寄,页面未加载完成或页面无锚点