简体   繁体   中英

Returning result from forEach results in undefined

I have a function that loops through a list using forEach and I want to return a result early (mimicking break ). But the function returns undefined. Why does it return undefined?

Here's the fiddle.

 const list = [1, 2, 3]; const test = () => { const rs = list.forEach(item => { return item }) return rs } const rs = test() console.log(rs)

The function forEach does not return a value. You'd be better off using find . At this point, it's unclear what you want to do with your loop so I'm assuming that you are trying to return a value based on a condition.

From MDN

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.

Also, the way you are calling your function is wrong. You are setting a variable inside a callback but never returning the variable. The test function returns nothing. Hence you get undefined.

You should return the value of the find function.

 const list = [1, 2, 3]; const test = () => { return list.find(item => { if(/* some condition */ item > 1) { return item } }) } const rs = test() console.log(rs)

If you want to know if there is something in the list you need this - note test needs to return something for the log to show anything

 const list = [1, 2, 3]; const test = () => { const rs = list.filter(item => { return item!=null }) return rs.length>0; } const rs = test() console.log(rs)

By definition, forEach return undefined. see this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

you can use map instead,which returns an array and do not forget to return it in a map

const list = [1, 2, 3];
const test = () => {
  const rs = list.map(item => {
      return item
  })
  return rs;
}
const rs = test()

Fix this problem this way.

 const list = [1, 2, 3]; const test = () => { const rs = []; list.forEach(item => { rs.push(item); }) return rs; } const rs = test(); console.log(rs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM