为什么.forEach返回未定义?

时间:2018-11-14 08:55:13

标签: 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"
        }
    ]
}];

我想使用.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

我想念什么?

3 个答案:

答案 0 :(得分:2)

根据mdn forEach

  

forEach()对每个数组元素执行一次回调函数;   与map()或reduce()不同,它总是返回未定义的值,并且   不可链接。典型的用例是在   链的末端。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

根据MDN:

.map()返回“一个新数组,每个元素都是回调函数的结果。”

.forEach()返回未定义。

如果要循环的代码是连续的,请使用.map(),否则使用.forEach()很好。

来源:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

相关问题