最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is .forEach returning undefined? - Stack Overflow

programmeradmin0浏览0评论

I know there already are multiple questions to this topic =%5Bjavascript%5D+return+forEach+undefined but none of this seemed to help me out.

So I have the following data:

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

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

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

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.

What am I missing?

I know there already are multiple questions to this topic https://stackoverflow./search?q=%5Bjavascript%5D+return+forEach+undefined but none of this seemed to help me out.

So I have the following data:

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

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

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

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.

What am I missing?

Share Improve this question asked Nov 14, 2018 at 8:55 wasddd_wasddd_ 1,0283 gold badges12 silver badges21 bronze badges 6
  • 1 Because forEach does not create a new object. It doesn't have a return value. You could simply return testArray; since you are mutating that object. – nbokmans Commented Nov 14, 2018 at 8:57
  • 1 Of course you can't return from forEach. – Mihai Alexandru-Ionut Commented Nov 14, 2018 at 8:57
  • 1 Use map instead of forEach – Erazihel Commented Nov 14, 2018 at 8:57
  • 3 You say you want to change the array in place, which is why you don't want to use map(), but then you go ahead and use code that tries to create a new array and return it... also testArray is a variable external to SOtest, so there's no need to return anything in the first place. – user5734311 Commented Nov 14, 2018 at 8:58
  • You missed the part of the documentation/specification, where it simply says "Return value: undefined". – tevemadar Commented Nov 14, 2018 at 9:02
 |  Show 1 more ment

3 Answers 3

Reset to default 5

forEach doesn't return anything. It just loops through elements and while looping you can change element data

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

According to mdn forEach

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

According to MDN:

.map() returns "A new array with each element being the result of the callback function."

.forEach() returns undefined.

If the code you're looping through is meant to be contiguous, use .map(), otherwise the .forEach() is fine.

Sources:

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

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

发布评论

评论列表(0)

  1. 暂无评论