英文:
I keep getting array not defined as an error when I am trying to push guesses into an array
问题
I am trying to push the correct guess into an array and print out how many guesses it took (in this case one, cause I'm just inputting the correct one) and then printing out what that guess was, but I am continually getting array not defined.
var guesses = [];
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (guess == num) {
guesses.push(guess);
numguesses = guesses.length;
message.innerHTML = "You got it! It took you " + numguesses + " tries and your guesses were " + guesses;
}
}
英文:
I am trying to push the correct guess into an array and print out how many guesses it took (in this case one, cause I'm just inputting the correct one) and then printing out what that guess was, but I am continually getting array not defined.
<!-- language: lang-js -->
var guesses = [];
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (guess == num) {
guesses.push(guess)
numguesses = array.length(guesses)
message.innerHTML = "You got it! It took you " + numguesses + " tries and your guesses were " + guesses;
}
答案1
得分: 1
问题在于你尝试计算猜测次数的方式。
array.length(guesses)
这不是有效的JavaScript语法。
发生的情况是,运行时认为 "array" 必须是你忘记定义的某个东西,因为你试图在其上调用 "length(guesses)"。
相反,你应该使用内置属性 .length
在 guesses
上,它存在于任何数组上。
英文:
Problem is the way you try to count the number of guesses.
array.length(guesses)
Is not valid Javascript syntax.
What happens is, the runtime thinks "array" must be something you forgot to define, since you try to call "length(guesses)" on it.
Instead you should use the inbuilt property .length
on guesses
which is present on any array.
答案2
得分: 1
正确获取 JavaScript 数组中元素数量的方式是:
arrayInstance.length
在你的情况下应该是:
guesses.length
了解更多,请阅读此处。
英文:
The correct way of getting the number of elements inside an array in js :
arrayInstance.length
In your case it would be
guesses.length
Read more here
答案3
得分: 0
在下面的示例中,使用了Set
来存储所有失败的猜测,并且还包括自定义验证。
示例中有详细的注释
// <form id="game">
const F = document.forms.game;
// 所有表单控件: <input>, <button>, <output>, 和 <fieldset>
const fc = F.elements;
// 状态区域
const Range = fc.range;
const Tries = fc.tries;
const Reset = fc.reset;
// 范围区域
const RSet = fc.rngSet;
const MIN = fc.min;
const MAX = fc.max;
const SET = fc.set;
// 尝试区域
const TSet = fc.trySet;
const TRY = fc.try;
// <label class="error">
const msg = document.querySelector(".error");
// 定义神秘数字
let N = 0;
// 定义一个 Set 来存储尝试
let attempts = new Set();
// 注册 "click" 事件到 <button id="set">
SET.onclick = setRange;
// 事件处理程序默认传递事件对象
function setRange(event) {
// 将 <input id="min"> 的值转换为数字
let min = parseInt(MIN.value);
// 将 <input id="max"> 的值转换为数字
let max = parseInt(MAX.value);
// 建立参数的条件
if (min < 1 || !min) {
min = 1;
MIN.value = min;
}
if (max < 1 || !max) {
max = 1;
MAX.value = max;
}
if (min > max) {
MIN.value = max;
MAX.value = min;
min = parseInt(MIN.value);
max = parseInt(MAX.value);
}
if (min === max) {
max = max + 1;
MAX.value = max;
}
// 显示数字范围
Range.value = `Range: ${min} to ${max}`;
// 禁用范围区域
RSet.disabled = true;
// 启用尝试区域
TSet.disabled = false;
// 为 <input id="try"> 设置范围值
TRY.min = min;
TRY.max = max;
// 在范围内确定一个随机数字
N = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(N)
}
// 注册 "submit" 事件到 <form>
F.onsubmit = tryNumber;
function tryNumber(event) {
// 阻止 <form> 重定向
event.preventDefault();
// 将 <input id="try"> 的值转换为数字
let min = parseInt(TRY.min);
let max = parseInt(TRY.max);
let guess = parseInt(TRY.value);
// 使用三元表达式定义所有可能的错误消息
let invalid = attempts.has(guess) ? `${guess} 已经尝试过了` :
guess < min ? `必须大于 ${min - 1}` :
guess > max ? `必须小于 ${max + 1}` :
isNaN(guess) ? `必须是正整数.` : ``;
/**
* 如果 "invalid" 为假...
* ...将 "guess" 添加到 Set attempts 中...
* ...从 'msg' 中删除 className "show"...
* ...从 'msg' data-msg 属性中删除值...
*/
if (!invalid) {
attempts.add(guess);
msg.classList.remove("show");
msg.dataset.msg = "";
/**
* ...否则...
* ...向 'msg' 添加 className "show"...
* ...并将无效消息分配给 'msg' 的 data-msg 属性。
*/
} else {
msg.classList.add("show");
msg.dataset.msg = invalid;
}
// 显示当前尝试的次数
Tries.value = `尝试次数: ${attempts.size}`;
// 清除 <input id="try">
TRY.value = "";
/**
* 如果 "guess" 等于 "N"...
* ...在 <output id="tries"> 中显示消息...
* ...禁用尝试区域...
* ...显示 <button id="reset">
*/
if (guess === N) {
Tries.value = `${N} 在 ${attempts.size} 次尝试中猜对了!`;
TSet.disabled = true;
Reset.style.display = "flex";
}
}
// 注册 "focus" 事件到 <input id="try">
TRY.onfocus = function() {
/**
* 一旦用户选择 'TRY',就从 'msg' 中删除 className "show"。
*/
msg.classList.remove("show");
}
// 注册 "reset" 事件到 <form>
F.onreset = resetGame;
// 重置 <form>
function resetGame(event) {
// 启用范围区域
RSet.disabled = false;
// 隐藏 <button id="reset">
Reset.style.display = "none";
// 清除 Set attempts
attempts.clear();
}
英文:
In the example below, a Set
is used to store all failed guesses and custom validation is included as well.
Details are commented in example
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
// <form id="game">
const F = document.forms.game;
// All form controls: <input>, <button>, <output>, and <fieldset>
const fc = F.elements;
// Status Area
const Range = fc.range;
const Tries = fc.tries;
const Reset = fc.reset;
// Range Area
const RSet = fc.rngSet;
const MIN = fc.min;
const MAX = fc.max;
const SET = fc.set;
// Try Area
const TSet = fc.trySet;
const TRY = fc.try;
// <label class="error">
const msg = document.querySelector(".error");
// Define mystery number
let N = 0;
// Define a Set to store tries
let attempts = new Set();
// Register "click" event to <button id="set">
SET.onclick = setRange;
// Event handler passes Event Object by default
function setRange(event) {
// Convert value of <input id="min"> to a number
let min = parseInt(MIN.value);
// Convert value of <input id="max"> to a number
let max = parseInt(MAX.value);
// Conditions to establish parameters
if (min < 1 || !min) {
min = 1;
MIN.value = min;
}
if (max < 1 || !max) {
max = 1;
MAX.value = max;
}
if (min > max) {
MIN.value = max;
MAX.value = min;
min = parseInt(MIN.value);
max = parseInt(MAX.value);
}
if (min === max) {
max = max + 1;
MAX.value = max;
}
// Display range of numbers
Range.value = `Range: ${min} to ${max}`;
// Disable Range Area
RSet.disabled = true;
// Enable Try Area
TSet.disabled = false;
// Set range values for <input id="try">
TRY.min = min;
TRY.max = max;
// Determine a random number within the range
N = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(N)
}
// Register "submit" event on <form>
F.onsubmit = tryNumber;
function tryNumber(event) {
// Stop <form> from redirecting
event.preventDefault();
// Convert values of <input id="try"> to numbers
let min = parseInt(TRY.min);
let max = parseInt(TRY.max);
let guess = parseInt(TRY.value);
// Ternary expresssion to define all possible error messages
let invalid = attempts.has(guess) ? `${guess} has already been tried` :
guess < min ? `Must be greater than ${min - 1}` :
guess > max ? `Must be less than ${max + 1}` :
isNaN(guess) ? `Must be a positive integer.` : ``;
/**
* If "invalid" is false...
* ...add "guess" to Set attempts...
* ...remove className "show" from 'msg'...
* ...romove the value from 'msg' data-msg attribute...
*/
if (!invalid) {
attempts.add(guess);
msg.classList.remove("show");
msg.dataset.msg = "";
/**
* ...otherwise...
* ...add className "show" to 'msg'...
* ...and assign the invalid message to 'msg' data-msg attribute.
*/
} else {
msg.classList.add("show");
msg.dataset.msg = invalid;
}
// Display the current number of tries
Tries.value = `Tries: ${attempts.size}`;
// Clear <input id="try">
TRY.value = "";
/**
* If "guess" equals "N"...
* ...display message in <output id="tries">...
* ...disable Try Area...
* ...show the <button id="reset">
*/
if (guess === N) {
Tries.value = `${N} was guessed correctly in ${attempts.size} tries!`;
TSet.disabled = true;
Reset.style.display = "flex";
}
}
// Register "focus" event to <input id="try">
TRY.onfocus = function() {
/**
* Remove className "show" form 'msg' as soon as the user
* selects 'TRY'.
*/
msg.classList.remove("show");
}
// Register "reset" event to <form>
F.onreset = resetGame;
// Resets the <form>
function resetGame(event) {
// Enable Range Area
RSet.disabled = false;
// Hide <button id="reset">
Reset.style.display = "none";
// Clear Set attempts
attempts.clear();
}
<!-- language: lang-css -->
@keyframes fade {
from {
opacity: 0.0;
}
to {
opacity: 1.0;
}
}
:root {
font: 2ch/1.15 "Segoe UI";
}
form>fieldset {
padding-bottom: 20px;
}
fieldset fieldset {
margin: 0;
padding: 0;
border: 0;
}
input,
button {
font: inherit;
height: 3.5ex;
margin-top: 12px;
}
input {
width: 6ch;
text-align: center
}
button {
display: inline-flex;
justify-content: center;
align-items: center;
padding: 17px 10px;
font-variant: small-caps;
cursor: pointer;
}
#reset {
display: none;
}
[disabled] {
opacity: 0.4;
}
.error {
display: flex;
justify-content: center;
align-items: center;
position: relative;
z-index: 1;
top: 5px;
opacity: 0.0;
}
.error::before {
content: attr(data-msg);
width: max-content;
padding: 5px 7px;
border-radius: 4px;
color: gold;
background: #444;
}
.show {
animation: fade 3s forwards;
}
.as-console-row::after {
width: 0;
font-size: 0;
}
.as-console-row-code {
width: 100%;
word-break: break-word;
}
.as-console-wrapper {
max-height: 20vh;
max-width: 20%;
margin-left: 80%;
}
<!-- language: lang-html -->
<form id="game" novalidate>
<fieldset>
<legend>
<!-- Status Area -->
<output id="range">&nbsp;</output><br>
<output id="tries">&nbsp;</output>
<button id="reset" type="reset">Play Again</button>
</legend>
<!-- Range Area -->
<fieldset id="rngSet">
<label>Min:
<input id="min" min="1" type="number">&nbsp;
</label>
<label>Max:
<input id="max" min="2" type="number">
</label>&nbsp;&nbsp;
<button id="set" type="button">Set Range</button>
</fieldset>
<!-- Try Area -->
<fieldset id="trySet" disabled>
<label>Your guess:&nbsp;
<input id="try" type="number" min="" max="">
</label>&nbsp;
<button type="submit">Guess</button>
<label for="try" class="error" data-msg></label>
</fieldset>
</fieldset>
</form>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论