You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript石头剪刀布循环时电脑随机选择值不更新问题求解

石头剪刀布游戏电脑选择不更新问题修复

错误根源

随机选择逻辑写在了computerPlay()函数的外部,脚本初始化阶段仅会执行1次随机计算,把结果存在全局变量randomValue中。后续5轮循环每次调用computerPlay()都只是返回这个第一次生成的固定值,不会重新生成随机选择。

具体错误点

  • 随机值生成语句let randomValue = myArray[Math.floor(Math.random() * myArray.length)]定义在全局作用域,脚本加载时就执行完毕,不会重复触发
  • computerPlay()函数内部没有编写随机计算逻辑,仅做固定值返回

修正后完整代码

const myArray = ['rock', 'paper', 'scissors']

function computerPlay() {
    // 每次调用函数时重新生成随机值,保证每轮选择不同
    const randomValue = myArray[Math.floor(Math.random() * myArray.length)]
    return randomValue;
}

function playRound(playerSelection, computerSelection) {
    // 兼容用户大小写输入
    playerSelection = playerSelection.toLowerCase()
    if (playerSelection == computerSelection) {
        console.log('It\'s a tie!')
        return
    } else if (
        (playerSelection == 'rock' && computerSelection == 'scissors') || 
        (playerSelection == 'paper' && computerSelection == 'rock') || 
        (playerSelection == 'scissors' && computerSelection == 'paper')
    ) {
        console.log('The human wins!');
        playerScore += 1;
        console.log(playerScore);
        return
    } else {
        console.log('The computer wins!');
        computerScore += 1;
        console.log(computerScore);
        return
    }
}

let playerScore = 0;
let computerScore = 0;
function game(){
    // 补全循环变量声明,避免全局污染
    for (let i = 0; i < 5; i++){
        const playerSelection = prompt('Choose your weapon');
        const computerSelection = computerPlay();
        playRound(playerSelection, computerSelection);
        console.log('Your score = ' + playerScore);
        console.log('Computer\'s score = ' + computerScore);
    }
}

game()

额外优化点

  • 补全循环变量i的let声明,原代码未声明变量会泄露到全局作用域,易引发未知bug
  • 新增玩家输入转小写逻辑,避免用户输入大写格式的选项时判定失效
  • 移除parseInt(0)冗余写法,0本身就是数字类型,无需额外转换
  • 移除不必要的console.log包裹,原代码console.log(playRound(...))和console.log(game())会额外打印undefined,因为两个函数没有返回值

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 19:48:20