簡體   English   中英

如何正確推入 JavaScript 中的空數組?

[英]How do you correctly push into Empty Array in JavaScript?

嘿,我正在創建一個簡單的星球大戰測驗,可以使用一些幫助。 謝謝!

JS(這里的想法是獲取值以稍后推送到數組中)

function addValues() {
  let value1 = document.getElementById('Q1').value;
  let value2 = document.getElementById('Q2').value;
  let value3 = document.getElementById('Q3').value;

  answerChoices.push(value1);
  answerChoices.push(value2);
  answerChoices.push(value3);

  console.log(value1);
}

HTML(添加 Html 以在單擊開始按鈕時替換索引)


<p id='timer'>Timer</p>
<div id='questions'>

  <h3>Where did Luke Skywalker Grow Up?</h3>
  <form id="Q1">
    <input type="radio" name="birthPlanet" id="Hoth" value="Hoth" /><label>Hoth</label>
    <input type="radio" name="birthPlanet" id="Tatooine" value="Tatooine" /><label>Tatooine</label>
    <input type="radio" name="birthPlanet" id="Endor" value="Endor" /><label>Endor</label>
  </form>

  <h3>What planet did the Death Star blow up?</h3>
  <form id="Q2">
    <input type="radio" name="Q2" id="Q2" value="Exogal" /><label>Exogal</label>
    <input type="radio" name="Q2" id="Q2" value="Yavin 4" /><label>Yavin 4</label>
    <input type="radio" name="Q2" id="Q2" value="Aldreaan" /><label>Aldreaan</label>
  </form>

  <h3>What year did Star War first come out?</h3>
  <form id="Q3">
    <input type="text" name="Q3" id="Q3" /><label>Enter Text Here</label>
  </form> <br />
  <button onclick="endButton()">Finish Quiz</button>
</div>

ARRAY let answerChoices= [];

可能這就是你想要的.. 嘗試片段

 function addValues(){ let value1 = document.querySelector('input[name="Q1"]:checked'); let value2 = document.querySelector('input[name="Q2"]:checked'); let value3 = document.querySelector('input[name="Q3"]'); let answerChoices = { 'Q1': value1.value, 'Q2': value2.value, 'Q3': value3.value } // console the hole values console.log(answerChoices); // console single value console.log(answerChoices.Q1); }
 <p id= 'timer'>Timer</p> <div id='questions'> <h3>Where did Luke Skywalker Grow Up?</h3> <form id="Q1"> <input type="radio" name="Q1" id="Hoth" value="Hoth" /><label>Hoth</label> <input type="radio" name="Q1" id="Tatooine" value="Tatooine" /><label>Tatooine</label> <input type="radio" name="Q1" id="Endor" value="Endor" /><label>Endor</label> </form> <h3>What planet did the Death Star blow up?</h3> <form id="Q2"> <input type="radio" name="Q2" id="Q2" value="Exogal" /><label>Exogal</label> <input type="radio" name="Q2" id="Q2" value="Yavin 4" /><label>Yavin 4</label> <input type="radio" name="Q2" id="Q2" value="Aldreaan" /><label>Aldreaan</label> </form> <h3>What year did Star War first come out?</h3> <form id="Q3"> <input type="text" name="Q3" id="Q3" /><label>Enter Text Here</label> </form> <br/> <button onclick="addValues()">Finish Quiz</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM