我有如下静态问题。我在博客中使用这些问题进行测验。
var quiz = {
"data": [
{
"question": "What is 10 + 5 ?",
"answer": "15",
},
{
"question": "What is 10 - 5 ?",
"answer": "5",
},
{
"question": "What is 10 + (- 5) ?",
"answer": "5",
},
{
"question": "What is -10 + 5 ?",
"answer": "-5",
},
{
"question": "What is -6 + (-6) ?",
"answer": "-12",
},
]
}
如何使问题和答案动态化?换句话说,每个数字将取 1 到 20 之间的值。答案将根据问题计算出来。
谢谢
最佳答案
function generateQuestion(template, min, max){
// Generate first random number
var numOne = Math.floor(Math.random() * (max - min) ) + min;
// Generate second random number
var numTwo = Math.floor(Math.random() * (max - min) ) + min;
// append first question part
var question = template[0];
// check if first number is negative to put brackets around the string
if(numOne < 0 )
question += "(" + numOne + ")";
else
question += numOne;
// append operator
question += " + ";
// check if second number is negative to put brackets around the string
if(numTwo < 0 )
question += "(" + numTwo + ")";
else
question += numTwo;
// append last part of question
question += template[1];
// return your object
return {
question: question,
answer: numOne + numTwo
};
}
var numberOfQuestions = 4;
var questions = [];
for(var i = 0; i < numberOfQuestions; i++)
questions.push(generateQuestion(["What is ", "?"], -20, 20))
console.log(questions);
关于javascript - 将静态问题转化为动态问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257671/