为了账号安全,请及时绑定邮箱和手机立即绑定

如何访问forEach中的外部变量?

如何访问forEach中的外部变量?

函数式编程 2023-07-29 16:15:09
这是代码片段。我想访问每个内部的 imagePath 数组。...const imagePath=[];             req.files.images.forEach(async (image) => {   let extName = path.extname(image.name);   var dest = path.join(__dirname, '..', 'public', 'images', 'items');   var imgPath = await saveFile(image, dest, itemName, extName);   imagePath.push(imgPath); // this line})...
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

通常,imagePath可以在循环中轻松访问forEach

但是,您的forEach回调是异步的。如果在循环console.log(imagePath)之后立即执行 a forEach,您将得到一个空数组。

一个简单的解决方法是使用forin循环。


查看完整回答
反对 回复 2023-07-29
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信