forEach回调中return true不生效,函数返回undefined问题排查
问题原因与解决方案
你的问题出在forEach的回调函数里的return true不会让外层的isTheTeamPlaying函数返回值——forEach的回调是独立的函数,里面的return只会终止当前回调的执行,不会中断整个forEach遍历,也不会让外层函数返回结果。因为外层函数没有任何return语句,所以默认返回undefined。
解决方法
方法1:使用Array.prototype.some()
some()方法会遍历数组,只要有一个元素满足条件就立即返回true并停止遍历,完全符合你的需求:
function isTheTeamPlaying(teamID, meetings) { return meetings.some(element => element.includes(teamID.toString())); } console.log(isTheTeamPlaying('1', ['0-1', '0-2', '0-3', '1-2'])); // 输出 true
方法2:使用for...of循环
手动循环可以让return直接作用于外层函数,找到匹配项后立即返回:
function isTheTeamPlaying(teamID, meetings) { const targetTeam = teamID.toString(); for (const element of meetings) { if (element.includes(targetTeam)) { return true; } } // 遍历完所有元素都没找到,返回false return false; } console.log(isTheTeamPlaying('1', ['0-1', '0-2', '0-3', '1-2'])); // 输出 true
方法3:设置标志位(不推荐,会遍历全部元素)
如果一定要用forEach,可以在外层定义一个标志变量,找到匹配项后修改标志,最后返回该标志:
function isTheTeamPlaying(teamID, meetings) { let isPlaying = false; meetings.forEach(element => { if (element.includes(teamID.toString())) { isPlaying = true; } }); return isPlaying; } console.log(isTheTeamPlaying('1', ['0-1', '0-2', '0-3', '1-2'])); // 输出 true
内容的提问来源于stack exchange,提问作者Johan Testas
相关产品推荐
相关产品推荐

