javascript - 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();
解决方案
您应该computerPlay()
为每个playRound()
. 所以试试这个:
function game() {
playRound(playerSelection, computerPlay());
playRound(playerSelection, computerPlay());
};
推荐阅读
- datetime - 带有谷歌驱动表的 Arduino 数据记录器
- javascript - div上的ScrollTop,Vuejs
- r - 提取文本中的第一个括号,其中包含一些观察的条件
- python - 在 Mac OSX Catalina 上运行 Python 3+ 时遇到问题
- powershell - 如何将大量 Powershell 脚本合并为一个
- spring - 我不能交朋友 Thymeleaf 和 Spring
- css - 如何排除css中的特定值
- java - Java 应用程序中 HTML 和 Microsoft Word 文件中的 Calibri (Body) 字体系列
- r - 选择具有不同 rowSums 条件的行
- javascript - 如何仅使用 Javasript 或 Typescript 将完整的 div 元素复制到剪贴板?