【发布时间】:2021-05-07 08:17:06
【问题描述】:
我正在尝试将我用 Python 制作的东西重写为 Javascript。我在传递变量时遇到了麻烦。这是一个文字游戏:变量newWord包含words数组中的一个随机单词,random被说出并显示2s,然后在createInputField中弹出一个输入字段,变量answer需要与checkAnswer中的random进行比较
我遇到的问题是checkAnswer 无法正常工作。每个answer 都显示为正确。其次,wordsCorrectCounter 保持在 1,尽管 answer 被测试为正确 3 次。
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var words = ["meget", "går", "mor"];
var wordsWrong = [];
var wordsCorrectCounter = 0;
var wordsWrongCounter = 0;
function textToAudio(random)
{
let msg = random;
let speech = new SpeechSynthesisUtterance();
speech.lang = "da-DK";
speech.text = msg;
speech.volume = 1;
speech.rate = 0.5;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
async function newWord(words)
{
if (words.length === 0){
endGame();
}
else {
var random = Math.floor(Math.random() * words.length);
document.getElementById("Empty").innerHTML = words[random];
textToAudio(words[random]);
await sleep(2000);
textToAudio(words[random]);
words.splice(random, 1);
document.getElementById("Empty").innerHTML = " ";
createInputField(words[random]);
}
};
function createInputField(random)
{
var answer = document.createElement("input");
answer.setAttribute("type", "text");
answer.id = "inputfield";
document.body.appendChild(answer)
let btn = document.createElement("button");
btn.id = "okBtn"
btn.innerHTML = "ok";
btn.type = "submit";
btn.name = "answerBtn";
document.body.appendChild(btn);
document.getElementById("okBtn").addEventListener("click", () => checkAnswer(answer))
}
function checkAnswer(random, answer)
{
if (answer === words[random]){
console.log("correct");
wordsCorrectCounter = +1;
console.log(wordsCorrectCounter)
document.getElementById("okBtn").remove();
document.getElementById("inputfield").remove();
newWord(words);
}
else{
console.log("wrong");
wordsWrongCounter = +1;
console.log(wordsWrongCounter)
document.getElementById("okBtn").remove();
document.getElementById("inputfield").remove();
newWord(words);
}
};
document.getElementById("startGame").addEventListener("click", () => newWord(words));
function endGame()
{
document.getElementById("Empty").innerHTML = "you are done!" + "Correct: " + wordsCorrectCounter + "Wrong: " + wordsWrongCounter;
};
<!DOCTYPE html>
<html>
<head>
<title>Aliyah's dictee spel</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="header">
<h1>Hej! Velkommen til Aliyahs diktee!</h1>
</div>
<div id="Random_word">
<h2 id="Empty">Click start to start</h2>
<button id="startGame">Start</button>
</div>
</body>
</html>
【问题讨论】:
标签: javascript if-statement parameter-passing