根据另一个数组的值抓取数据

时间:2018-05-20 06:58:06

标签: javascript arrays

我目前正在尝试创建一个随机生成一组问题及其相应答案的页面。 但是,我无法弄清楚如何将问题与相应的答案相匹配。

对于这些问题,我想出了一组数组,为了答案,我想出了另一个:

//Array for Questions
var myWords = [
    'Test1',
    'Test2',
    'Test3',
    'Test4',
    'Test5',
    'Test6',
    'Test7',
    'Test8',
    'Test9',
    'Test10',
    'Test11',
    'Test12',
    'Test13',
    'Test14',
    'Test15'
]

//Array for Answers
var myAnswers = [
    'Answer1',
    'Answer2',
    'Answer3',
    'Answer4',
    'Answer5',
    'Answer6',
    'Answer7',
    'Answer8',
    'Answer9',
    'Answer10',
    'Answer11',
    'Answer12',
    'Answer13',
    'Answer14',
    'Answer15'
]

基于此,我使用以下脚本从第一个数组中选择10个独特的随机问题:

    //randomly pick 10 words
    while(selectWords.length < 10){
        var randomWord = myWords[Math.floor(Math.random() * myWords.length)]
        if(selectWords.indexOf(randomWord) > -1) continue;
        selectWords[selectWords.length] = randomWord;
    }

如何将每个问题与第二个数组中的相应答案相关联?我希望输出显示在这样的表中:

问题1 |答案1

提前致谢!

2 个答案:

答案 0 :(得分:4)

使用包含问题和答案的对象的单个数组:

var myQuestions = [
    { question: "Test1", answer: "Answer1" },
    { question: "Test2", answer: "Answer2" },
    ...
];

然后,您可以将这些对象放入selectWords数组中,并在使用时访问.question.answer属性。

答案 1 :(得分:0)

最好一次用答案定义问题,但是如果你坚持使用你提供的输入,另一个选择是map他们在一起,这样当你选择一个随机的时候,你有一个包含问题和答案的对象。

var myWords=['Test1','Test2','Test3','Test4','Test5','Test6','Test7','Test8','Test9','Test10','Test11','Test12','Test13','Test14','Test15'];
var myAnswers=['Answer1','Answer2','Answer3','Answer4','Answer5','Answer6','Answer7','Answer8','Answer9','Answer10','Answer11','Answer12','Answer13','Answer14','Answer15'];

const questionsAndAnswers = myWords.map((question, i) => ({ question, answer: myAnswers[i] }));
const selectWords = Array.from({ length: 10 }, () => (
  questionsAndAnswers.splice(Math.floor(Math.random() * questionsAndAnswers.length), 1)[0]
));
console.log(selectWords);