我在这里做一个掷硬币的应用程序,除了coinTossResult()
在resultText.innerHTML
中显示尾巴的这一部分外,一切都很好,而当我在下一行将其登录到控制台时,它显示了头部。否则,当coinTossResult()
在resultText.innerHTML
中显示尾时,它与console.log匹配。不知道为什么会这样。
resultText.innerHTML = `The Computer chose ${compChoice} and it is a ${(coinTossResult())}`
console.log(compChoice, coinTossResult());
下面是我的完整代码:
const btnChoices = document.querySelectorAll('.options');
const resultText = document.querySelector('.result-text');
const tossWinText = document.querySelector('.toss-winner');
const turnText = document.querySelector('.turn-text');
const btnArea = document.querySelector('.buttons');
let playerChoice =[];
let compChoice = [];
function whoseTurn(){
if(Math.floor(Math.random() * 2) === 0){
turnText.innerHTML = 'Computer will flip the coin';
btnArea.style.display = "none";
const options = ['head', 'tails'];
const random = Math.floor(Math.random() * options.length);
compChoice = options[random];
resultText.innerHTML = `The Computer chose ${compChoice} and it is a ${(coinTossResult())}`
console.log(compChoice, coinTossResult());
}else{
turnText.innerHTML = 'Player will flip the coin';
btnChoices.forEach(function(e){
e.addEventListener('click', function(){
if(e.classList.contains('head')){
playerChoice = 'head';
}else{
playerChoice = 'tails';
}
resultText.innerHTML = `The Player chose ${playerChoice} and it is a ${coinTossResult()}`
if(playerChoice === coinTossResult()){
tossWinText.innerHTML = 'Player has won the Toss';
}else{
tossWinText.innerHTML = 'Computer has won the Toss';
}
})
})
}
}
function coinTossResult(){
const opt = ['head', 'tails'];
const ran = Math.floor(Math.random() * opt.length);
const cho = opt[ran];
return cho;
}
whoseTurn();
你调用了两次方法
coinTossResult()
将其分配给一个变量并console.log它