为什么.forEach返回未定义? [英] Why is .forEach returning undefined?
问题描述
我知道此主题已经有多个问题 https://stackoverflow.com/搜索?q =%5Bjavascript%5D + return + forEach +未定义,但是这些似乎都帮不了我.
I know there already are multiple questions to this topic https://stackoverflow.com/search?q=%5Bjavascript%5D+return+forEach+undefined but none of this seemed to help me out.
所以我有以下数据:
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
而不使用输出 来实现的目标是,因为我不想要一个新数组,我只想覆盖现有的数组,如下所示:
What I want to achieve with the output without using .map()
or .reduce
since I do not want a new array, I just want to overwrite the existing one, is the following:
[{
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
:
The function I have looks something like this - please note that it has some helper fns which you can ignore - it's just about that the fn returns 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
.
Now the forEach
itself works just fine when executed by itself in the console - but as soon as I want to return it, it equals undefined
.
我想念什么?
推荐答案
forEach
不返回任何内容.它只是循环遍历元素,循环时您可以更改元素数据
forEach
doesn't return anything. It just loops through elements and while looping you can change element data
因此您可以将功能SOtest
更改为
And so you can change your function SOtest
to
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;
}
这篇关于为什么.forEach返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!