JS石头剪刀布游戏函数末尾返回undefined问题求助
石头剪刀布游戏末尾返回undefined的原因及解决方法
你遇到的末尾返回undefined的核心原因是最后一行的console.log(playGame());在打印playGame函数的返回值,而playGame函数内部没有显式的return语句——JavaScript中任何没有返回值的函数都会默认返回undefined。
你的playGame函数内部已经通过console.log输出了游戏过程和结果,但它本身没有返回任何内容,所以当你用console.log包裹调用它时,就会额外打印出这个默认的undefined。
解决方法
直接修改最后一行代码,去掉外层的console.log,直接调用函数即可:
playGame();
可选优化(让函数返回结果)
如果你希望playGame能返回结果字符串供外部处理,可以修改函数如下:
const playGame = () => { const userChoice = getUserChoice('scissors'); const computerChoice = getComputerChoice(); const resultText = 'You threw ' + userChoice + ' '+ 'AI threw ' + computerChoice; const winnerText = determineWinner(userChoice, computerChoice); console.log(resultText); console.log(winnerText); // 返回结果组合 return `${resultText}\n${winnerText}`; } // 此时调用console.log(playGame())就会打印结果而不是undefined console.log(playGame());
另外补充一个小细节:getUserChoice函数的else分支里return;也会返回undefined,但这只在输入无效时触发,你说程序能正常返回userInput,所以这不是当前问题的原因。
内容的提问来源于stack exchange,提问作者jarvic1207
相关产品推荐
相关产品推荐

