首页 > 解决方案 > Javascript - 避免将重复的问题放入数组中

问题描述

我的班级中有这个片段,它使用 chance.js 生成一个随机数:

this.askQuestions = [];        
this.questions = JSON.parse(this.questionsData);
for(let i = 0; i < 10; i++){
   let n = chance.integer({min: 0, max: this.questions.length - 1});
   this.askQuestions.push({
       questionIndex: n,
       question: this.questions[n].question,
       choices: this.questions[n].possibleAnswers
   });
}

我正在使用它从包含 2000 多个条目的 json 文件中提取随机问题。在调试期间,我设置了固定的10迭代次数,我正在努力让用户设置一个介于 1 和 100 之间的数字。我注意到有时我会重复一些问题,我不希望这样可以发生。任何人都可以建议我一种方法来检查并最终将重复的条目替换到问题数组中吗?

标签: javascriptnode.jsarrayschancejs

解决方案


在不使用任何库的情况下解决问题的一种方法是创建一个可能值数组并在随机选择元素时删除它们:

const N = this.questions.map((_, i) => i);

for (let i = 0; i < 10; i++) {
    const n = Math.floor(Math.round() * N.length);
    N.splice(n, 1); // remove N[n]

    this.askQuestions.push({
        questionIndex: n,
        question: this.questions[n].question,
        choices: this.questions[n].possibleAnswers
    });
}

推荐阅读