如果我從問題中選擇“q1”,我該如何從答案中選擇第一個陣列?
這是我現在的代碼:
questions = ["q1", "q2", "q3"]
answers = [
["r", "f", "f", "f"],
["r2", "f2", "f2", "f2"],
["r3", "f3", "f3", "f3"]
];
function pickQuestion() {
if (questions.length > 0) {
question = questions[Math.floor(Math.random() * questions.length)];
questions.splice(questions.indexOf(question), 1);
// find array in answers that matches question and remove it
answers.splice(answers.indexOf(question), 1);
return ([question, answerArray]);
} else {
return ("End of questions");
}}
uj5u.com熱心網友回復:
這里你的代碼在作業;)
questions = ["q1", "q2", "q3"]
answers = [
["r", "f", "f", "f"],
["r2", "f2", "f2", "f2"],
["r3", "f3", "f3", "f3"]
];
function pickQuestion() {
if (questions.length > 0) {
randomIndex = Math.floor(Math.random() * questions.length)
question = questions[randomIndex];
let answer = answers[randomIndex]
// Remove played question/answer
questions.splice(randomIndex, 1);
answers.splice(randomIndex, 1);
return ([question, answer]);
} else {
return ("End of questions");
}
}
let a = pickQuestion()
console.log(a)
uj5u.com熱心網友回復:
function pickQuestion() {
if (questions.length) {
// set the index to a random number
let index = Math.floor(Math.random() * questions.length);
const question = questions[index];
const answerArray = answers[index];
questions.splice(index, 1);
answers.splice(index, 1);
return ([question, answerArray]);
} else {
return ("End of questions");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/375499.html
標籤:javascript 数组
上一篇:JQuery-單擊驗證ID添加類
