javascript - 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 之间的数字。我注意到有时我会重复一些问题,我不希望这样可以发生。任何人都可以建议我一种方法来检查并最终将重复的条目替换到问题数组中吗?
解决方案
在不使用任何库的情况下解决问题的一种方法是创建一个可能值数组并在随机选择元素时删除它们:
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
});
}
推荐阅读
- python - 如何在python中创建一个新的.txt文件
- json - 将数据从动态创建的字段发送到控制器
- reactjs - 直接在类 react-redux 中编写调度函数
- c - 如何使用 sscanf 提取子字符串?
- python - num+=i>num 行后面的逻辑是什么
- firebase - 如何在 Flutter 中启用/禁用 Firebase Crashlytics
- reactjs - 如何使用 .map 函数评估 React 中对象中的每个值
- database - Structuring of data for users in firebase
- php - php将关联数值数组转换为普通数组
- git - Git不断复制文件并在文件名末尾附加'2'