JavaScript石头剪刀布游戏始终平局及报错问题求助
JavaScript石头剪刀布项目问题排查与修复
问题1:无参数调用determineWinner()导致始终显示平局
最后一行console.log(determineWinner())未传入任何参数,此时函数内的userChoice和computerChoice均为undefined,第一个判断条件userChoice === computerChoice直接成立,因此返回'Tie',这就是你看到始终平局的原因。
问题2:调用getUserChoice()未传参导致toLowerCase()报错
playGame函数里var userChoice = getUserChoice()没有传参,userInput会是undefined,执行userInput.toLowerCase()时自然抛出TypeError: Cannot read properties of undefined (reading 'toLowerCase')错误。
问题3:函数命名不规范(可选优化)
getcomputerChoice不符合JavaScript驼峰命名规范,建议改为getComputerChoice,提升代码可读性。
修正后的完整代码
const getUserChoice = (userInput) => { // 先判断输入是否存在,避免undefined报错 if (!userInput) { console.log('请输入有效的选项:rock、paper或scissors'); return; } userInput = userInput.toLowerCase(); if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') { return userInput; } else { console.log('Error! 请输入rock、paper或scissors'); } }; // 修正驼峰命名 const getComputerChoice = () => { const randomNumber = Math.floor(Math.random() * 3); switch (randomNumber) { case 0: return 'rock'; case 1: return 'paper'; case 2: return 'scissors'; } }; const determineWinner = (userChoice, computerChoice) => { // 先校验参数有效性 if (!userChoice || !computerChoice) { return '无效的游戏选项'; } if (userChoice === computerChoice) { return 'Tie'; } if (userChoice === 'rock') { return computerChoice === 'paper' ? 'computer won' : 'user won'; } if (userChoice === 'paper') { return computerChoice === 'scissors' ? 'computer won' : 'user won'; } if (userChoice === 'scissors') { return computerChoice === 'rock' ? 'computer won' : 'user won'; } }; const playGame = (userInput) => { // 传入用户选择参数 const userChoice = getUserChoice(userInput); console.log('你的选择:', userChoice); const computerChoice = getComputerChoice(); console.log('电脑的选择:', computerChoice); console.log('结果:', determineWinner(userChoice, computerChoice)); }; // 调用示例:传入有效选项 playGame('scissors');
使用说明
调用playGame时需传入有效选项,比如playGame('rock')、playGame('paper')或playGame('scissors'),即可正常运行游戏。
内容的提问来源于stack exchange,提问作者Ali Semih Çamkerten
相关产品推荐
相关产品推荐

