javascript - 将用户输入(问答)存储在数组中并检索答案

标签 javascript html arrays

我是 JavaScript 初学者,在这项任务中我必须执行以下操作;

  • 允许用户在 html 页面中输入问题和答案对,该页面将存储在数组中。
  • 当询问数组中的一个问题时检索答案(不同的框、标签)
  • 按下按钮时重置框

到目前为止,我只知道如何将用户输入存储在一个数组中,在按下按钮时追加它并显示它。

如何在同一个数组中拥有两个不同的对象(问题和答案),这两个对象将由用户成对输入,并在再次输入问题时仅检索答案? 它的工作原理类似于手动机器人。

var myArr = [];

function pushData() {
  // get value from the input text
  var inputText = document.getElementById('inputText').value;

  // append data to the array
  myArr.push(inputText);

  var pval = "";

  for (i = 0; i < myArr.length; i++) {
    pval = pval + myArr[i] + "<br/>";
  }

  // display array data
  document.getElementById('pText').innerHTML = pval;
}
<!DOCTYPE html>

<html>

<head>
  <title</title>
    <meta charset="windows-1252">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>

  <input type="text" name="text" id="inputText" />
  <button onclick="pushData();">Show</button>
  <p id="pText"></p>

</body>

</html>

最佳答案

为什么不使用对象呢?这样,您就可以存储问题/答案对,其中问题作为键,答案作为其值。试试这个:

var myObj = {};

function pushData() {
  // get value from the input text
  var question = document.getElementById('inputQuestion').value;
  var answer = document.getElementById('inputAnswer').value;

  // add data to the object
  myObj[question] = answer;
}

function getAnswer() {
  var question = document.getElementById('inputRetrieveQuestion').value;

  if (myObj[question]) {
    document.getElementById('pText').innerHTML = myObj[question];
  }
}
<html>

<body>
  <h3> Enter a Question/Answer </h3>
  Question <input type="text" name="question" id="inputQuestion" /> Answer <input type="text" name="answer" id="inputAnswer" />
  <button onclick="pushData()">Submit</button>
  </br>

  <h3> Retrieve an Answer </h3>
  Question <input type="text" name="question" id="inputRetrieveQuestion" />
  <button onclick="getAnswer()">Submit</button>
  </br>

  Answer:
  <div id="pText"></div>
</body>

</html>

关于javascript - 将用户输入(问答)存储在数组中并检索答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46658258/

相关文章:

javascript - 如何在javascript中验证window.prompt?

javascript - 使用 vue.js 动态设置 v-for

c# - 参数复杂对象作为未定义进入 JavaScript 函数

html - 将宽度和省略号设置为表格的 <td> 元素

c# - 为什么 List<T>.Add 和 List<T>.Remove 将元素复制到新数组中而不是实际添加和删除?

javascript - AngularJS 和 i18next

javascript - 如何设置 SVG 路径的样式来拍摄图像?

javascript - 动态创建html

c - 在不使用字符串库 C 的情况下删除行中的尾随字符

c++ - 为什么 C++ 会这样?