Как мне найти массив в массиве на основе индекса другого массива?

#javascript #arrays

#язык JavaScript #массивы

Вопрос:

Если я выберу «q1» из вопросов, как мне выбрать также первый массив из ответов?

Это мой код прямо сейчас:

 questions = ["q1", "q2", "q3"] answers = [  ["r", "f", "f", "f"],  ["r2", "f2", "f2", "f2"],  ["r3", "f3", "f3", "f3"] ];  function pickQuestion() { if (questions.length gt; 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"); }}  

Комментарии:

1. сохраните это Math.floor(Math.random() * questions.length)] как index и используйте это для доступа к нужному элементу в обоих массивах?

2. И вообще, почему ты сплайсируешься? Вопрос заключается в выборе вопроса, а код объединяет два массива.

Ответ №1:

Вот ваш код в работе 😉

 questions = ["q1", "q2", "q3"] answers = [  ["r", "f", "f", "f"],  ["r2", "f2", "f2", "f2"],  ["r3", "f3", "f3", "f3"] ];  function pickQuestion() {  if (questions.length gt; 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) 

Ответ №2:

 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");  } }