首页 > 解决方案 > 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 };
}

标签: javascriptmongoose

解决方案


当您想为循环中的每个项目实现一个函数时,最好使用 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 };
}));

推荐阅读