首页 > 解决方案 > JS 对象循环返回未定义,而 Lodash 映射返回值

问题描述

我在 JS 中有一个循环,一旦循环完成,值将返回为 null,如果我出于相同目的使用 lodash,它会返回结果。

这是我尝试过的:

JS:

const jsRows = Object.entries(response).forEach(([key, row]) => {
    return row;
});
console.log(jsRows) ==> Output undefined

罗达什:

const loRows = map(response, row => {
    return row;
});
console.log(loRows) ==> Output Array

标签: javascriptlodash

解决方案


.forEach()函数总是返回undefined。它与.map()函数完全不同。本机 JavaScriptArray.prototype.map()还返回一个新数组。

.forEach()函数用于在不需要包含每个数组值转换的新结果的情况下对数组的每个元素“做某事”。.map()另一方面,该函数用于基于每个数组元素的转换将数组转换为新数组。


推荐阅读