gpt4 book ai didi

javascript - 将 array.foreach 的结果存储在另一个数组中

转载 作者:行者123 更新时间:2023-12-01 01:12:06 24 4
gpt4 key购买 nike

我有一个这样的代码示例:

  const iam = ['dd', 'aaa', 'cc'];
async function bigTest() {
async function details() {
const arr = [];
const files = [];
iam.forEach(async (i) => {
arr.push({
name: 'test',
});

files.push(arr);
return files;
});
}

const result = await details();
console.log(result);
}
bigTest();

我想将arr的最终结果存储在数组files中,但它返回未定义

在循环内部,它返回数组,但在详细信息函数之外,它返回未定义

最佳答案

您应该使用函数map

由于您需要 async 声明,map 函数中的数组包含 Promises,因此您需要按如下方式解析它们:

Promise.all(files);

const iam = ['dd', 'aaa', 'cc'];
async function bigTest() {
async function details() {
const files = iam.map(async(name) => {
return { name };
});

return Promise.all(files);
}

const result = await details();
console.log(result);
}

bigTest();
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将 array.foreach 的结果存储在另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55072457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com