要做个简单的考试页面,记录一下遇到的小问题
填空题 要根据后端显示的答案数量,有几个填空,显示几个输入框
//填空题根据答案现实输入框个数
this.questions.forEach(question => {
if (question.type=== '填空题') {
const answerArray = new Array(question.ANS_SIZE).fill(''); // 初始化为空字符串数组
// 检查并确保USER_ANS是数组,如果不是,则使用默认空数组
const userAnswers = Array.isArray(question.USER_ANS) ? question.USER_ANS : [];
userAnswers.forEach((answer, index) => {
if (index < answerArray.length) {
answerArray[index] = answer; // 将后台答案填充到数组
}
});
this.$set(this.answers, question.QUE_ID, answerArray);
}
});
这段代码的作用是根据题目类型为填空题的题目,初始化答案数组并根据用户已输入的答案进行填充。
- 遍历
this.questions
数组中的每个题目; - 如果题目的类型为填空题(
question.type === '填空题'
); - 初始化一个长度为
question.ANS_SIZE
的空字符串数组answerArray
; - 检查
question.USER_ANS
是否为数组,如果不是则将其设置为空数组; - 遍历
userAnswers
数组,将用户已输入的答案填充到answerArray
中; - 使用
this.$set
方法将answerArray
设置为this.answers
对象中question.QUE_ID
对应的属性值。