繁体   English   中英

从 forEach 返回结果导致未定义

[英]Returning result from forEach results in undefined

我有一个使用forEach循环遍历列表的函数,我想尽早返回结果(模仿break )。 但该函数返回未定义。 为什么它返回未定义?

这是小提琴。

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

forEach函数不返回值。 你最好使用find 在这一点上,尚不清楚您想对循环做什么,所以我假设您正在尝试根据条件返回一个值。

来自MDN

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

此外,您调用函数的方式是错误的。 您在回调中设置了一个变量,但从不返回该变量。 test函数不返回任何内容。 因此你得到未定义。

您应该返回find函数的值。

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

如果你想知道列表中是否有你需要的东西 - 注意测试需要返回一些东西让日志显示任何东西

 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)

根据定义,forEach 返回 undefined。 看到这个: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

您可以改用 map,它返回一个数组,不要忘记在 map 中返回它

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

用这种方法解决这个问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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