为什么"片段文本"未定义?



我正在创建一个涉及解密文本的小猜谜游戏,但是我的JavaScript代码中有一个变量无法正常工作。这个变量称为pieceOfText,应该等于由 3 段编码文本组成的数组生成的随机文本。但是,当我检索所述变量的值时,它会输出undefined

这是我现在的代码:

function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
<!DOCTYPE html>
<html>
<HEAD>
<META CHARSET="UTF-8" />
<TITLE>Decryption Guessing Game</TITLE>
</HEAD>
<BODY>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<SCRIPT LANGUAGE="Javascript">
</SCRIPT>
</BODY>
</html>

注释掉的行可能会阻止我的猜谜游戏正常运行,因为pieceOfText设置为undefined。当我发现这一点时,我目前正在进行一些调试。我发现的一个类似困境的问题更倾向于 ECMAScript 6(我不确定我是否在使用它),而我发现的其他问题甚至与 JavaScript 无关。那么,是什么原因造成的,我该如何解决?

你写了Math.random而不是Math.random()(你忘了实际调用函数):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Decryption Guessing Game</title>
</head>
<body>
<p id="para">Text:</p>
<form name="game" action="get" onsubmit="return validateForm()">
Decrypt: <input type="text" name="text">
<input type="submit" value="Check!">
</form>
<script>
function randomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} // defines the function that gets a random number
var text = ['smell', 'cat', 'jump']; // pieces of text to decrypt
var encryptedText = []; // the decrypted pieces of text.
for (var i = 0; i < text.length; i++) {
encryptedText.push(window.btoa(text[i]));
}
var pieceOfText = encryptedText[randomInt(0, 2)];
console.log(pieceOfText);
/* document.getElementById('para').innerHTML += " " + pieceOfText; */
function validateForm() {
var form = document.forms['game']['text'];
var input = form.value;
if (input == "") {
alert("Enter your answer within the input.");
return false;
} else if (!(/^[a-zA-Z0-9-]*$/.test(input))) {
alert("Your input contains illegal characters.");
return false;
} else if (input != window.atob(pieceOfText)) {
alert("Incorrect; try again.");
location.reload();
} else {
alert("Correct!");
location.reload();
}
}
</script>
</body>
</html>

最新更新