首页 > 解决方案 > 为什么 .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.

我错过了什么?

标签: javascriptarrays

解决方案


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;
}

推荐阅读