用JavaScript打乱API测验答案



我从API中随机抽取10个问题,但目前,正确答案设置为始终为"D"。我正在努力寻找一种方法来随机化答案,这样正确的答案就不会总是"D"或我在代码中设置的任何其他选项。JSON是一个对象数组,但由于correct_answers是对象中与correct_asswer分离的内部数组,这就是我感到困惑的地方。如果我打乱内部数组,那只会打乱选项A、B和C。D在该内部数组之外仍然是一个单独的属性。

希望有人能帮忙。提前谢谢。点击此处查看应用程序屏幕截图

这是JSON的示例

{
"response_code": 0,
"results": [
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "easy",
"question": "What is the most expensive weapon in Counter-Strike: Global Offensive?",
"correct_answer": "Scar-20/G3SG1",
"incorrect_answers": [
"M4A1",
"AWP",
"R8 Revolver"
]
},
{
"category": "Entertainment: Cartoon & Animations",
"type": "multiple",
"difficulty": "easy",
"question": "Who is the only voice actor to have a speaking part in all of the Disney Pixar feature films? ",
"correct_answer": "John Ratzenberger",
"incorrect_answers": [
"Tom Hanks",
"Dave Foley",
"Geoffrey Rush"
]
}
}

这是我迄今为止的代码

const main = () => {
let score = 0;
let questionCounter = 0;
let availableQuestions = [];
let currentQuestion = {};
// target DOM elements
const question = document.querySelector(".question-container");
const choices = document.querySelectorAll(".choice-txt");
const selection = document.querySelectorAll(".choice-container");
// API endpoint     
const endPoint = `https://opentdb.com/api.php?amount=10&difficulty=easy&type=multiple`;
// fetch data from the API
fetch(endPoint)
.then((res)=>{
return res.json();
})
.then((json)=>{
question.innerHTML = `<p>
${json.results[0].question}
</p>`
// populate the 4 answer options
// currently the correct answer is always D
choices[0].innerText = `${json.results[0].incorrect_answers[0]}`
choices[1].innerText = `${json.results[0].incorrect_answers[1]}`
choices[2].innerText = `${json.results[0].incorrect_answers[2]}`
choices[3].innerText = `${json.results[0].correct_answer}`
})
.catch((err)=>{
console.log(`An error occured ${err}`);
})

selection[0].addEventListener("click",()=>{
console.log(`Answer "A" selected`)
})
selection[1].addEventListener("click",()=>{
console.log(`Answer "B" selected`)
})
selection[2].addEventListener("click",()=>{
console.log(`Answer "C" selected`)
})
selection[3].addEventListener("click",()=>{
console.log(`Answer "D" selected`)
})
}
main();

为此,您需要将正确/不正确的答案放在一个对象数组中。(进行归一化(

我用了费雪-耶茨洗牌。看看这里


洗牌部件

function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}

此外,我还改进了代码的可读性。

规范化部分

// fetch data from the API
fetch(endPoint)
.then((res) => {
return res.json();
}).then((json) => {
question.innerHTML = 
`<p>
${json.results[0].question}
</p>`
let answers = json.results[0].incorrect_answers.map(f => {
return {
isCorrect: false,
text: f
}
});
answers.push({
isCorrect: true,
text: json.results[0].correct_answer
});
// populate the shuffled 4 answer options
shuffle(answers).forEach((answer, index) => {
choices[index].innerText = `${answer.text}`
})
})
.catch((err) => {
console.log(`An error occured ${err}`);
})

测试部件

function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
// Create sample data.
const results = [
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "easy",
"question": "What is the most expensive weapon in Counter-Strike: Global Offensive?",
"correct_answer": "Scar-20/G3SG1",
"incorrect_answers": [
"M4A1",
"AWP",
"R8 Revolver"
]
},
{
"category": "Entertainment: Cartoon & Animations",
"type": "multiple",
"difficulty": "easy",
"question": "Who is the only voice actor to have a speaking part in all of the Disney Pixar feature films? ",
"correct_answer": "John Ratzenberger",
"incorrect_answers": [
"Tom Hanks",
"Dave Foley",
"Geoffrey Rush"
]
}
];
// Putting wrong answers
let answers = results[0].incorrect_answers.map(f => {
return {
isCorrect: false,
text: f
}
});
// Also putting correct answer
answers.push({
isCorrect: true,
text: results[0].correct_answer
});
//Logging shuffled answers
shuffle(answers).forEach((answer, index) => {
console.log(answer);
})

对于我的答案,我没有使用fetch,所以您可以看到结果。

我的答案得到正确和不正确的答案,并将它们放入一个数组中。然后这个数组被随机化。

let json = {
"response_code": 0,
"results": [{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "easy",
"question": "What is the most expensive weapon in Counter-Strike: Global Offensive?",
"correct_answer": "Scar-20/G3SG1",
"incorrect_answers": [
"M4A1",
"AWP",
"R8 Revolver"
]
},
{
"category": "Entertainment: Cartoon & Animations",
"type": "multiple",
"difficulty": "easy",
"question": "Who is the only voice actor to have a speaking part in all of the Disney Pixar feature films? ",
"correct_answer": "John Ratzenberger",
"incorrect_answers": [
"Tom Hanks",
"Dave Foley",
"Geoffrey Rush"
]
}
]
};
let answers = [];
let test = json.results[0];
answers.push({
"correct": 1,
"answer": test["correct_answer"]
});
test.incorrect_answers.forEach(function(a) {
answers.push({
"correct": 0,
"answer": a
});
});
answers.sort(() => (Math.random() > 0.5) ? 1 : -1)
console.log(answers)

最新更新