javascript - map 和 for...of 给出不同的结果
问题描述
我正在尝试遍历项目中的数组值。
如果我遍历 Array.map() 它会给我一个空数组,但是如果我使用 for...of 循环进行迭代,我会得到正确的结果(带有值的新数组)。
const items = await Item.find({ itemId: items.map(item => item) });
for (item of items) {
itemsArr.push(await Item.find({ itemId: item };
}
解决方案
当您想为循环中的每个项目实现一个函数时,最好使用 Array.map
var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
解决您的 array.map 问题的最佳案例是
Promise.all(items.map( async (e) => {
itemsArr.push(await Item.find({ itemId: e };
}));
推荐阅读
- php - 预订系统的 PHP 对象/数组算法
- python - Django rest 框架简单模型序列化器列表视图需要永远显示 10 条记录
- apache-nifi - 如何在 Apache NIFI 中将机器学习应用于流数据
- regex - Notepad++ 正则表达式 - 如何从此列表中删除代理?
- sas - 将Stata“egen,group”转换为SAS
- kubernetes - kubernetes 容器中的 redis-cluster 在 spinup 时重新启动
- angular - Angular 订阅功能未在 http 404 错误上触发
- javascript - Modify Apollo React function to use parameters
- r - 如何根据多组标准找到平均值、最大值和最小值
- javascript - 将数组写入javascript中的元素的未知错误?