简体   繁体   English

如何在javascript中将提交的测验答案数组与正确答案数组进行比较

[英]How to compare an array of submitted quiz answers with an array of correct answers in javascript

I've built a multiple choice quiz. 我建立了一个选择题测验。 Some of the questions have a single correct answer (using radio input), others have multiple correct answers (checkboxes). 一些问题有一个正确答案(使用无线电输入),另一些问题有多个正确答案(复选框)。

When the user submits the quiz I collect all of the checked radio boxes and checkboxes and push the id of the answer to an array which heads to the server. 当用户提交测验时,我将收集所有选中的单选框和复选框,并将答案的ID推送到一个指向服务器的数组。 It looks like this: 看起来像这样:

userAnswers = [ '1c', '2d', '3a', '3b', '3c', '3d', '4b', '5c', '5d', '6d', '7c', '7d' ]

On the server I have an array of all the correct answers. 在服务器上,我有所有正确答案的数组。

correctAnswers = [ '1c', '2d', '3b', '3d', '4b', '5a', '5d', '6d', '7c', '7d' ]

I've tried using underscore's _.difference function to compare the arrays but that doesn't give me a complete comparison. 我试过使用下划线的_.difference函数比较数组,但这并不能给我完整的比较。

Can anyone help me devise a way to grade these quizzes? 谁能帮助我设计一种对这些测验进行评分的方法? I think the problem is that some of the questions have multiple answers so technically someone could tick all 4 checkboxes or just one, it makes it harder to compare them. 我认为问题在于某些问题有多个答案,因此从技术上讲,某人可以勾选所有4个复选框或仅勾选一个,这使得比较它们变得更加困难。

Maybe using arrays isn't the best way to do this, any suggestions are appreciated! 也许使用数组不是做到这一点的最佳方法,任何建议都值得赞赏!

Maybe using arrays isn't the best way to do this 也许使用数组不是执行此操作的最佳方法

Yes, you really should use an appropriate data structure for this: 是的,您确实应该为此使用适当的数据结构:

answers = [
  ['c'], // 1
  ['d'], // 2
  ['a', 'b', 'c', 'd'], // 3
  ['b'], // 4
  ['c', 'd'], // 5
  ['d'], // 6
  ['c', 'd'] // 7
]

You could also use an object for "named" questions (instead of indexing them), and possibly drop the array wrapper for single-choice questions, but I'd argue for arrays because of their simplicity here. 您也可以将一个对象用于“命名”问题(而不是为其编制索引),并且可以删除单选问题的数组包装器,但是我建议使用数组,因为它们在这里很简单。

If you want to use your original format as input (eg because it's easier to type or your server doesn't support nesting URL query parameters), you can easily convert it to the nested arrays. 如果您想使用原始格式作为输入(例如,因为键入更容易或者服务器不支持嵌套URL查询参数),则可以轻松地将其转换为嵌套数组。

Comparing the results with the correct answers question-for-question should be trivial then. 因此,将结果与正确的问题进行逐项比较比较容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM