首页 > 解决方案 > javascript函数在它应该是随机的时返回相同的值

问题描述

当我调用函数 game() 时,即使我将其设置为返回随机值,它也会不断从 computerSelection 返回相同的值。当我自己调用 computerPlay() 时,它每次调用时都会给出随机值,但在变量 computerSelection 下的 game() 函数中使用时不会给出随机值。

  function computerPlay() {
  const plays = ["rock", "paper", "scissors"];
  return plays[Math.floor(Math.random() * plays.length)];
};



function playRound(playerSelection, computerSelection) {
  if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
    console.log('paper beat rock')
    return ('paper beats rock')
  } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'rock') {
    console.log('its a tie, try again!')
    return ('its a tie, try again!')
  } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
    console.log('rock beats scissors')
    return ('rock beats scissors')
  } else {
    console.log('wut')
  }
};

function game() {
      playRound(playerSelection, computerSelection);
      playRound(playerSelection, computerSelection);
};



const playerSelection = "Rock";
let computerSelection = computerPlay();

标签: javascriptfunction

解决方案


您应该computerPlay()为每个playRound(). 所以试试这个:

function game() {
      playRound(playerSelection, computerPlay());
      playRound(playerSelection, computerPlay());
};

推荐阅读