从数组值计算分数

时间:2014-08-27 08:00:14

标签: javascript

正如标题所暗示的那样。我该怎么做?

我必须使用纯粹的JS,而且我真的很擅长(就像真的很新)。请原谅我的noob问题。 :)

我的数组看起来像这样:

var questionArr = [
{
    'questionId' : 'Question1',
    'question' : 'Q1: How many Objects are there? ',
    'choices' : [
        {"id" : "10", "tf" : false, "points" : 0},
        {'id' : "11", "tf" : false, "points" : 0},
        {'id' : "12", "tf" : false, "points" : 0},
        {'id' : "15", "tf" : true, "points" : 10},
        {'id' : "16", "tf" : false, "points" : 0}
    ],
    'Mchoice' : false,
    'completed' : false
},
{
    'questionId' : 'Question2',
    'question' : 'Q2: some Question will go here? ',
    'choices' : [
            {'id' : "answer1", "tf" : true, "points" : 5},
            {'id' : "answer2", "tf" : false, "points" : 1},
            {'id' : "answer3", "tf" : false, "points" : 1},
            {'id' : "answer4", "tf" : true, "points" : 10}
        ],
        'Mchoice' : true,
        'completed' : false
    },

并且正在进行中。

每个选项都显示为单选按钮或复选框。取决于" Mchoice"虚假/真实。当我创建它们时,它们中的每一个都得到了" tf"我可以检查所选答案是否正确。

我的目标是在背景中计算分数,如果答案正确则添加分数,如果答案错误则减去分数,但在减去时我不能低于0。在回答完所有问题并按下提交按钮后,我想查看每个问题的总分数中有多少。对于问题1而言,问题1中的X为10,而在页面末尾则为总得分:X中的100,我们只能说100就是可以达到的总点数。

我希望你知道我的意思并且可以帮助我,因为我现在真的坚持了一天或更长时间。不知道如何实现这一目标。再说一次,我真的是JS的新手,所以如果这最终是一个非常愚蠢的问题,请不要苛刻我:)

1 个答案:

答案 0 :(得分:0)

首先,这不是一个愚蠢的问题。您需要拥有所选择的选项,您可以逐个检查它们或先将它们存储在一个数组中然后计算得分(就像我做的那样):

var questionArr = [
    {
        'questionId' : 'Question1',
        'question' : 'Q1: How many Objects are there? ',
        'choices' : [
            {"id" : "10", "tf" : false, "points" : 0},
            {'id' : "11", "tf" : false, "points" : 0},
            {'id' : "12", "tf" : false, "points" : 0},
            {'id' : "15", "tf" : true, "points" : 10},
            {'id' : "16", "tf" : false, "points" : 0}
        ],
        'Mchoice' : false,
        'completed' : false
    },
    {
        'questionId' : 'Question2',
        'question' : 'Q2: some Question will go here? ',
        'choices' : [
                {'id' : "answer1", "tf" : true, "points" : 5},
                {'id' : "answer2", "tf" : false, "points" : 1},
                {'id' : "answer3", "tf" : false, "points" : 1},
                {'id' : "answer4", "tf" : true, "points" : 10}
            ],
            'Mchoice' : true,
            'completed' : false
    }
]
var selectedChoicesArray = ["10", "answer4"] //choices that user selected as answers
var sum = 0;
for(var i=0; i<questionArr.length; i++) {
    for(var j=0; j<questionArr[i].choices.length; j++){
        if(questionArr[i].choices[j].id == selectedChoicesArray[i]) //the choice which user selected
            sum += questionArr[i].choices[j].points //matched choice's points will be added to the sum
    }
}
alert("Sum: "+sum);

在这种情况下,当selectedChoicesArray呈现时,用户选择了question1的第一选择和答案2的第四选择,因此,总和将是10!如果你把它改成:

var selectedChoicesArray = ["15", "answer1"];
在这种情况下,总和将是15。希望你能理解那些循环,它们相当简单。

<强> See the demo here

相关问题