admin管理员组

文章数量:1794759

Javascript的坑:函数里forEach使用return语句

Javascript的坑:函数里forEach使用return语句

在函数内出于方便,使用了forEach来进行循环遍历,当某一项符合条件时,返回false,否则返回true。不过我发现函数结果返回始终为true,且if里的条件为真,代码如下:

const allInItemSettings = (tpls, subsStgs) => { tpls.forEach(id => { if(subsStgs?.itemSettings?.[id] === undefined) { return false // 即使执行也不会返回 } }) return true } // 返回值始终为true

后来查资料发现forEach里的return其实是充当`continue`的作用,即本次循环之后的语句不再执行,不会终止循环,更不会结束函数返回。

如果要实现预期的功能,有两个解决方法:

1. 将返回值存在变量里,在forEach之外返回该变量

优点:代码量少,返回值较灵活 缺点:forEach会完全执行,对于数组元素较多的情况效率较低

const allInItemSettings = (tpls, subsStgs) => { let allIn = true tpls.forEach(id => { if(subsStgs?.itemSettings?.[id] === undefined) { allIn = false } }) return allIn }

2. 在要返回的地方抛出一个异常,在捕获异常的操作里进行返回

优点:forEach循环会在符合条件的时候终止 缺点:返回值无法通过异常传递,适合返回值比较固定的情况

const allInItemSettings = (tpls, subsStgs) => { try { tpls.forEach(id => { if(subsStgs?.itemSettings?.[id] === undefined) { throw new Error('not all in') // 抛出异常 } }) } catch(e) { if(e.message == 'not all in') { return false // 这里捕获异常并返回 } } return true }

总结:

  • 数组内置的方法参数为函数的情况下,其return语句不可作为外层函数的返回语句(这一点实在是大意了)。
  • forEach的return语句作用类似于continue,终止当次循环。
  • 若要提前终止forEach的循环,可以使用异常处理

本文标签: 语句函数JavaScriptreturnforEach