javascript - 为什么 .forEach 返回未定义?
问题描述
我知道这个主题已经有多个问题https://stackoverflow.com/search?q=%5Bjavascript%5D+return+forEach+undefined但这些似乎都没有帮助我。
所以我有以下数据:
const testsMap = {
0: ["just", "test"],
1: ["bla", "asdf"]
}
const testArray = [{
id: "1",
segments: null,
tests: [{
id: "1",
segments: "1"
},
{
id: "2",
segments: "0"
}
]
},
{
id: "2",
segments: "1",
tutorials: [{
id: "1",
segments: "1"
},
{
id: "2",
segments: "0"
}
]
}];
我想在不使用.map()
或.reduce
不想要新数组的情况下使用输出来实现,我只想覆盖现有数组,如下所示:
[{
display: true,
id: "1",
segments: null,
tests: [{
display: true,
id: "1",
segments: "1",
newSegments: ["bla", "asdf"]
},
{
display: true,
id: "2",
segments: "0",
newSegments: ["just", "test"]
}
]
},
{
display: false,
id: "2",
segments: "1",
tutorials: [{
id: "1",
segments: "1"
},
{
id: "2",
segments: "2"
}
]
}];
我的函数看起来像这样 - 请注意它有一些你可以忽略的辅助 fns - 它只是 fn 返回undefined
:
function SOtest () {
const returnedValue = testArray.forEach(test => {
test.newSegments = test.segments ? testsMap[test.segments] : [];
test.display = helperFn(); // will add true/false to the test prop
if (test.display) {
test.tests.map(t => {
t.newSegments = t.segments ? testsMap[t.segments] : [];
t.display = helperFn(); // will add true/false to the test prop
})
}
return test;
})
return returnedValue;
}
现在,forEach
在控制台中自行执行时,它本身可以正常工作 - 但只要我想返回它,它就等于undefined
.
我错过了什么?
解决方案
forEach
不返回任何东西。它只是循环遍历元素,在循环时您可以更改元素数据
所以你可以改变你的SOtest
功能
function SOtest () {
testArray.forEach(test => {
test.newSegments = test.segments ? testsMap[test.segments] : [];
test.display = helperFn(); // will add true/false to the test prop
if (test.display) {
test.tests.map(t => {
t.newSegments = t.segments ? testsMap[t.segments] : [];
t.display = helperFn(); // will add true/false to the test prop
})
}
})
return testArray;
}
推荐阅读
- docker - 在 docker env 中使用 nginx 和 node js 应用程序在 30 秒后得到 503
- javascript - jquery - 计算输入的多个数字
- python - Python 'tuple' 对象没有属性 'find'
- tomcat - 向Tomcat发送POST请求时如何解决浏览器中的Javascript fetch API错误?
- python - 字段 'id' 需要一个数字,但得到了
我正在构建一个 BlogApp 我遇到了一个错误。
我想要做什么:-(我想要它做什么)
我正在过滤具有类似
tags
. 但是当我尝试过滤时,错误一直显示 -字段“id”需要一个数字,但在 0x000001
- c++ - 对二维数组进行排序...发生异常 (C++)
- javascript - 在 SQLite (Node/Express) 中更新数据
- javascript - Firebase 存储:“put”预期的 Blob 或文件中的参数无效
- python - 检查一个列表中的一项是否存在于另一个字符串 Python 列表中
- c# - 让对象的组件在足够远的地方禁用一次