从 forEach 返回结果会导致未定义



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

这是小提琴。

const list = [1, 2, 3];
const test = () => {
const rs = list.forEach(item => {
return item
})
return rs
}
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 返回未定义。 看到这个: 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()

函数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.forEach(item => {
rs.push(item);
})
return rs;
}
const rs = test();
console.log(rs);

最新更新