为什么 .forEach 返回未定义?

was*_*dd_ -2 javascript arrays

我知道这个主题已经有多个问题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"
        }
    ]
}];
Run Code Online (Sandbox Code Playgroud)

我想在不使用.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"
        }
    ]
}];
Run Code Online (Sandbox Code Playgroud)

我的函数看起来像这样 - 请注意,它有一些你可以忽略的辅助 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;
}
Run Code Online (Sandbox Code Playgroud)

现在,forEach当在控制台中单独执行时,它本身工作得很好 - 但一旦我想返回它,它就等于undefined.

我缺少什么?

Nit*_*ang 5

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;
}
Run Code Online (Sandbox Code Playgroud)