随机生成一份试卷,试卷的种类分为单选、多选、判断三种题型。nodejs6.0 mysql

背景:从数据库中,随机生成一份试卷,试卷的种类分为单选、多选、判断三种题型。

首先我需要生成随机数id(在这之前我需要知道数据库中各个题型的题数,这样我才能设置随机数),并依据生成的随机数id,去查找对应的题目。而在js的数组操作中,有filter、splice、concat、every、find等等。我需要从数据库中取出特定的数据,而我返回的是一组对象,那么我需要过滤出特定的部分。

代码如下:

var danxuan = getRandomNum(danxuan_count,20);
var duoxuan = getRandomNum(duoxuan_count,5);
var panduan = getRandomNum(panduan_count,10);
将生成的随机数存到example中,
var example = {danxuan:danxuan.sort(sortNumber),duoxuan:duoxuan.sort(sortNumber),panduan:panduan.sort(sortNumber)}

//查找数据库
models.Answer.findAll().then(function(result){
var danxuanList = result.filter(t => t.exampleType=="单选题");//nodejs6.0支持 =>
var duoxuanList = result.filter(t => t.exampleType=="多选题");
var panduanList = result.filter(t => t.exampleType=="判断题");
  //新建对象
var exampleList = {duoxuan:[],danxuan:[],panduan:[]};
//根据随机生成的编号id,去各个list中找相应的数据
example.danxuan.forEach(function(i,v){

exampleList.danxuan.push(danxuanList[i]);
})
example.duoxuan.forEach(function(i,v){
exampleList.duoxuan.push(duoxuanList[i]);
})
example.panduan.forEach(function(i,v){
exampleList.panduan.push(panduanList[i]);
})
res.json(exampleList);//试卷生成完毕
});
原文地址:https://www.cnblogs.com/Allen-node/p/5511047.html