你不知道的forEach函数

简介: 你不知道的forEach函数

给大家推荐一个实用面试题库

1、前端面试题库 (面试必备)            推荐:★★★★★

地址:web前端面试题库

老实说我不喜欢用forEach,因为它导致的一些bug总是这么不经意,盘点我不喜欢的原因

原因一:不支持处理异步函数

先看一个例子:

async function test() {
    let arr = [3, 2, 1]
    arr.forEach(async item => {
        const res = await mockSync(item)
        console.log(res)
    })
    console.log('end')
}
function mockSync(x) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
                resolve(x)
        }, 1000 * x)
    })
}
test()
我们期望的结果是:
3
2 
1
end
但是实际上会输出:
end
1
2
3

JavaScript中的forEach()方法是一个同步方法,它不支持处理异步函数。如果你在forEach中执行了异步函数,forEach()无法等待异步函数完成,它会继续执行下一项。这意味着如果在forEach()中使用异步函数,无法保证异步任务的执行顺序。

替代forEach的方式

1.方式一

可以使用例如map()、filter()、reduce()等,它们支持在函数中返回Promise,并且会等待所有Promise完成。

使用map()和Promise.all()来处理异步函数的示例代码如下:

const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(num * 2);
    }, 1000);
  });
}
const promises = arr.map(async (num) => {
  const result = await asyncFunction(num);
  return result;
});
Promise.all(promises).then((results) => {
  console.log(results); // [2, 4, 6, 8, 10]
});

由于我们在异步函数中使用了await关键字,map()方法会等待异步函数完成并返回结果,因此我们可以正确地处理异步函数。

方式二 使用for循环来处理异步函数

const arr = [1, 2, 3, 4, 5];
async function asyncFunction(num) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(num * 2);
    }, 1000);
  });
}
async function processArray() {
  const results = [];
  for (let i = 0; i < arr.length; i++) {
    const result = await asyncFunction(arr[i]);
    results.push(result);
  }
  console.log(results); // [2, 4, 6, 8, 10]
}
processArray();

原因二:无法捕获异步函数中的错误

如果异步函数在执行时抛出错误,forEach()无法捕获该错误。这意味着即使在异步函数中出现错误,forEach()仍会继续执行。

原因三:除了抛出异常以外,没有办法中止或跳出 forEach() 循环

forEach()方法不支持使用break或continue语句来跳出循环或跳过某一项。如果需要跳出循环或跳过某一项,应该使用for循环或其他支持break或continue语句的方法。

原因四:forEach 删除自身元素,index不可被重置

在forEach中我们无法控制 index 的值,它只会无脑的自增直至大于数组的 length 跳出循环。所以也无法删除自身进行index重置,先看一个简单例子:

let arr = [1,2,3,4]
arr.forEach((item, index) => {
    console.log(item); // 1 2 3 4
    index++;
});

原因五:this指向问题

在forEach()方法中,this关键字引用的是调用该方法的对象。但是,在使用普通函数或箭头函数作为参数时,this关键字的作用域可能会出现问题。在箭头函数中,this关键字引用的是定义该函数时所在的对象。在普通函数中,this关键字引用的是调用该函数的对象。如果需要确保this关键字的作用域正确,可以使用bind()方法来绑定函数的作用域。以下是一个关于forEach()方法中this关键字作用域问题的例子:

const obj = {
  name: "Alice",
  friends: ["Bob", "Charlie", "Dave"],
  printFriends: function () {
    this.friends.forEach(function (friend) {
      console.log(this.name + " is friends with " + friend);
    });
  },
};
obj.printFriends();

在这个例子中,我们定义了一个名为obj的对象,它有一个printFriends()方法。在printFriends()方法中,我们使用forEach()方法遍历friends数组,并使用普通函数打印每个朋友的名字和obj对象的name属性。但是,当我们运行这个代码时,会发现输出结果为:

undefined is friends with Bob
undefined is friends with Charlie
undefined is friends with Dave

这是因为,在forEach()方法中使用普通函数时,该函数的作用域并不是调用printFriends()方法的对象,而是全局作用域。因此,在该函数中无法访问obj对象的属性。

为了解决这个问题,可以使用bind()方法来绑定函数的作用域,或使用箭头函数来定义回调函数。以下是使用bind()方法解决问题的代码示例:

const obj = {
  name: "Alice",
  friends: ["Bob", "Charlie", "Dave"],
  printFriends: function () {
    this.friends.forEach(
      function (friend) {
        console.log(this.name + " is friends with " + friend);
      }.bind(this) // 使用bind()方法绑定函数的作用域
    );
  },
};
obj.printFriends();

在这个例子中,我们使用bind()方法来绑定函数的作用域,将该函数的作用域绑定到obj对象上。运行代码后,输出结果为:

Alice is friends with Bob 
Alice is friends with Charlie 
Alice is friends with Dave

通过使用bind()方法来绑定函数的作用域,我们可以正确地访问obj对象的属性。

另一种解决方法是使用箭头函数。由于箭头函数没有自己的this,它会继承它所在作用域的this。因此,在箭头函数中,this关键字引用的是定义该函数时所在的对象。代码略

原因六: forEach性能比for循环低

for:for循环没有额外的函数调用栈和上下文,所以它的实现最为简单。

forEach:对于forEach来说,它的函数签名中包含了参数和上下文,所以性能会低于 for 循环。

原因七:会跳过已删除或者未初始化的项

// 跳过未初始化的值
const array = [1, 2, /* empty */, 4];
let num = 0;
array.forEach((ele) => {
  console.log(ele);
  num++;
});
console.log("num:",num);
//  1
//  2 
//  4 
// num: 3
// 跳过已删除的值
const words = ['one', 'two', 'three', 'four'];
words.forEach((word) => {
  console.log(word);
  if (word === 'two') {
  // 当到达包含值 `two` 的项时,整个数组的第一个项被移除了
  // 这导致所有剩下的项上移一个位置。因为元素 `four` 正位于在数组更前的位置,所以 `three` 会被跳过。
    words.shift(); //'one' 将从数组中删除
  }
}); // one // two // four
console.log(words); // ['two', 'three', 'four']

原因八:forEach使用不会改变原数组

forEach() 被调用时,不会改变原数组,也就是调用它的数组。但是那个对象可能会被传入的回调函数改变

// 例子一
const array = [1, 2, 3, 4]; 
array.forEach(ele => { ele = ele * 3 }) 
console.log(array); // [1,2,3,4]
// 解决方式,改变原数组
const numArr = [33,4,55];
numArr.forEach((ele, index, arr) => {
    if (ele === 33) {
        arr[index] = 999
    }
})
console.log(numArr);  // [999, 4, 55]
// 例子二
const changeItemArr = [{
    name: 'wxw',
    age: 22
}, {
    name: 'wxw2',
    age: 33
}]
changeItemArr.forEach(ele => {
    if (ele.name === 'wxw2') {
        ele = {
            name: 'change',
            age: 77
        }
    }
})
console.log(changeItemArr); // [{name: "wxw", age: 22},{name: "wxw2", age: 33}]
// 解决方式
const allChangeArr = [{    name: 'wxw',    age: 22}, {    name: 'wxw2',    age: 33}]
allChangeArr.forEach((ele, index, arr) => {
    if (ele.name === 'wxw2') {
        arr[index] = {
            name: 'change',
            age: 77
        }
    }
})
console.log(allChangeArr); // // [{name: "wxw", age: 22},{name: "change", age: 77}]

好了,我还是使用for...of去替代forEach吧

给大家推荐一个实用面试题库

1、前端面试题库 (面试必备)            推荐:★★★★★

地址:web前端面试题库

相关文章
Sampling Procedure 和 Sample-drawing Procedure, SAP QM里的双胞胎?
Sampling Procedure 和 Sample-drawing Procedure, SAP QM里的双胞胎?
Sampling Procedure 和 Sample-drawing Procedure, SAP QM里的双胞胎?
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8055 2
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18252 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
2天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
773 0
|
8天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1474 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2606 8