如何使用javascript随机添加表单输入值

How to randomly add form input values with javascript?

本文关键字:表单 输入 添加 随机 何使用 javascript      更新时间:2023-09-26

例如,假设我有一个数组中某个问题的答案池。

如何将3个随机答案和1个正确答案呈现为表单输入的值?

让我试试这是半伪代码真的很快。。

var answerList = [1, 2, 3, ,4 ,5 ,6 ,7, 8, 9, 10];
var questionIdArrays = [1]
var question1 = {
   questionId: 1,
   question: "What is 5 + 5?",
   correctAnswer: 5
  }
get random question from questionIdArrays
because questionIdArray is 1, get questionId 1
display question1's question in <h1> element
randomly display correctAnswer in 1 of the 4 input values
randomly grab 3 answers from answerList and place them randomly in the remaining 3 input values

希望这是有道理的!最困难的部分是答案的随机输出,我对此感到困惑。提前感谢!

Zero the correct answer from the answerList
create loop
use Math.random() to get a number from the list
test if result is zero
  if it is then get another number
store value 
zero out result