I keep getting array not defined as an error when I am trying to push guesses into an array

huangapple go评论54阅读模式
英文:

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(&quot;guess&quot;).value);
  let message = document.getElementById(&quot;message&quot;);
  if (guess == num) {
    guesses.push(guess)
    numguesses = array.length(guesses)
    message.innerHTML = &quot;You got it! It took you &quot; + numguesses + &quot; tries and your guesses were &quot; + guesses;
  }

答案1

得分: 1

问题在于你尝试计算猜测次数的方式。

array.length(guesses)

这不是有效的JavaScript语法。

发生的情况是,运行时认为 "array" 必须是你忘记定义的某个东西,因为你试图在其上调用 "length(guesses)"。

相反,你应该使用内置属性 .lengthguesses 上,它存在于任何数组上。

英文:

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 .lengthon 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 -->

// &lt;form id=&quot;game&quot;&gt;
const F = document.forms.game;
// All form controls: &lt;input&gt;, &lt;button&gt;, &lt;output&gt;, and &lt;fieldset&gt;
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;
// &lt;label class=&quot;error&quot;&gt;
const msg = document.querySelector(&quot;.error&quot;);
// Define mystery number
let N = 0;
// Define a Set to store tries
let attempts = new Set();
// Register &quot;click&quot; event to &lt;button id=&quot;set&quot;&gt;
SET.onclick = setRange;
// Event handler passes Event Object by default
function setRange(event) {
// Convert value of &lt;input id=&quot;min&quot;&gt; to a number
let min = parseInt(MIN.value);
// Convert value of &lt;input id=&quot;max&quot;&gt; to a number
let max = parseInt(MAX.value);
// Conditions to establish parameters
if (min &lt; 1 || !min) {
min = 1;
MIN.value = min;
}
if (max &lt; 1 || !max) {
max = 1;
MAX.value = max;
}
if (min &gt; 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 &lt;input id=&quot;try&quot;&gt;
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 &quot;submit&quot; event on &lt;form&gt;
F.onsubmit = tryNumber;
function tryNumber(event) {
// Stop &lt;form&gt; from redirecting
event.preventDefault();
// Convert values of &lt;input id=&quot;try&quot;&gt; 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 &lt; min ? `Must be greater than ${min - 1}` :
guess &gt; max ? `Must be less than ${max + 1}` :
isNaN(guess) ? `Must be a positive integer.` : ``;
/**
* If &quot;invalid&quot; is false...
* ...add &quot;guess&quot; to Set attempts...
* ...remove className &quot;show&quot; from &#39;msg&#39;...
* ...romove the value from &#39;msg&#39; data-msg attribute...
*/
if (!invalid) {
attempts.add(guess);
msg.classList.remove(&quot;show&quot;);
msg.dataset.msg = &quot;&quot;;
/**
* ...otherwise...
* ...add className &quot;show&quot; to &#39;msg&#39;...
* ...and assign the invalid message to &#39;msg&#39; data-msg attribute.
*/
} else {
msg.classList.add(&quot;show&quot;);
msg.dataset.msg = invalid;
}
// Display the current number of tries
Tries.value = `Tries: ${attempts.size}`;
// Clear &lt;input id=&quot;try&quot;&gt;
TRY.value = &quot;&quot;;
/**
* If &quot;guess&quot; equals &quot;N&quot;...
* ...display message in &lt;output id=&quot;tries&quot;&gt;...
* ...disable Try Area...
* ...show the &lt;button id=&quot;reset&quot;&gt;
*/
if (guess === N) {
Tries.value = `${N} was guessed correctly in ${attempts.size} tries!`;
TSet.disabled = true;
Reset.style.display = &quot;flex&quot;;
}
}
// Register &quot;focus&quot; event to &lt;input id=&quot;try&quot;&gt;
TRY.onfocus = function() {
/**
* Remove className &quot;show&quot; form &#39;msg&#39; as soon as the user 
* selects &#39;TRY&#39;.
*/
msg.classList.remove(&quot;show&quot;);
}
// Register &quot;reset&quot; event to &lt;form&gt;
F.onreset = resetGame;
// Resets the &lt;form&gt;
function resetGame(event) {
// Enable Range Area
RSet.disabled = false;
// Hide &lt;button id=&quot;reset&quot;&gt;
Reset.style.display = &quot;none&quot;;
// Clear Set attempts
attempts.clear();
}

<!-- language: lang-css -->

@keyframes fade {
from {
opacity: 0.0;
}
to {
opacity: 1.0;
}
}
:root {
font: 2ch/1.15 &quot;Segoe UI&quot;;
}
form&gt;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 -->

&lt;form id=&quot;game&quot; novalidate&gt;
&lt;fieldset&gt;
&lt;legend&gt;
&lt;!-- Status Area --&gt;
&lt;output id=&quot;range&quot;&gt;&amp;nbsp;&lt;/output&gt;&lt;br&gt;
&lt;output id=&quot;tries&quot;&gt;&amp;nbsp;&lt;/output&gt;
&lt;button id=&quot;reset&quot; type=&quot;reset&quot;&gt;Play Again&lt;/button&gt;
&lt;/legend&gt;
&lt;!-- Range Area --&gt;
&lt;fieldset id=&quot;rngSet&quot;&gt;
&lt;label&gt;Min: 
&lt;input id=&quot;min&quot; min=&quot;1&quot; type=&quot;number&quot;&gt;&amp;nbsp;
&lt;/label&gt;
&lt;label&gt;Max: 
&lt;input id=&quot;max&quot; min=&quot;2&quot; type=&quot;number&quot;&gt;
&lt;/label&gt;&amp;nbsp;&amp;nbsp;
&lt;button id=&quot;set&quot; type=&quot;button&quot;&gt;Set Range&lt;/button&gt;
&lt;/fieldset&gt;
&lt;!-- Try Area --&gt;
&lt;fieldset id=&quot;trySet&quot; disabled&gt;
&lt;label&gt;Your guess:&amp;nbsp; 
&lt;input id=&quot;try&quot; type=&quot;number&quot; min=&quot;&quot; max=&quot;&quot;&gt;
&lt;/label&gt;&amp;nbsp;
&lt;button type=&quot;submit&quot;&gt;Guess&lt;/button&gt;
&lt;label for=&quot;try&quot; class=&quot;error&quot; data-msg&gt;&lt;/label&gt;
&lt;/fieldset&gt;
&lt;/fieldset&gt;
&lt;/form&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月22日 04:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定