设置空数组索引

时间:2016-02-04 14:58:58

标签: javascript arrays node.js

我有一个数组,可以解答给定问题的学生答案。

如果学生给出答案,它会被插入到当前索引的数组中,如[ "answer", undefined, // student has not given answer "answer2", ]

之后,我可以读取数组并将条目映射到给定的问题数组

这种情况:

if (answers[questionindex] === undefined)

的工作原理。 (循环遍历数组,只输出“没有给出答案”undefined

但是当LAST答案未定义(1个或更多)时它不起作用 他们只是不存在(当然)。

如何将这些字段设置为var testResults = { addRoom: function(Id, teacher) { // room pseudoconstructor this[Id] = { created: moment(), runningProblem: false, time: 0, // holds the countdown for the current problem getTime: function() { // returns the countdown-counter return this.time; }, Id: Id, teacher: teacher, getCurrentSolution: function() { return math.eval(this.testProblems[this.getCurrentProblemIndex()].problem); }, getTimeTaken: function() { return this.getCurrentProblemTimeLimit() - this.time; }, getCurrentProblemTimeLimit: function() { return this.testProblems[this.getCurrentProblemIndex()].timeLimit; }, getCurrentProblemIndex: function() { return this.testProblems.length - 1; }, addTestProblem: function(problem, timeLimit) { var solution = math.eval(problem); this.testProblems.push({problem: problem, timeLimit: timeLimit, solution: solution}); console.dir(this.testProblems); }, testProblems: [], updatePercentages: function(name) { function round(num) { return +(Math.round(num + "e+2") + "e-2"); } console.log('updating percentages'); console.log('answers length ' + this.students[name].givenAnswers.length); var timeSum = 0; for(var i = 0; i < this.students[name].givenAnswers.length; i++ ) { timeSum += this.students[name].givenAnswers[i].takenTime; } var timeAvg = timeSum / this.students[name].givenAnswers.length; console.log('timeAvg for ' + name + ' ' + timeAvg); this.students[name].avgTime = round(timeAvg); var correctSum = 0; for(var j = 0; j < this.students[name].givenAnswers.length; j++ ) { if (this.students[name].givenAnswers[j].correct) { correctSum++; } } var correctAvg = correctSum / this.students[name].givenAnswers.length; console.log('correctAvg for ' + name + ' ' + correctAvg); this.students[name].avgCorrect = round(correctAvg) * 100; }, addGivenStudentAnswer: function(name, answer, takenTime, index) { console.log('adding answer ' + name + ' ' +answer+ ' ' + takenTime); var correct = this.getCurrentSolution() == answer; if (typeof this.students[name].givenAnswers[index] === 'undefined') { this.students[name].givenAnswers[index] = ({ answer: answer, takenTime: takenTime, correct: correct }); this.updatePercentages(name); //console.dir(this.students[name].givenAnswers); return true; } else { console.log('attempt at double answer. not saved'); return false; } }, addStudent: function(name) { if (!(this.students[name])) { this.students[name] = { studentName : name, avgTime: 0, avgCorrect: 0, givenAnswers: [] } } console.dir(this); }, students: {} }; console.dir(this); }, deleteRoom: function(Id) { delete this[Id]; console.log('room deleted from testResults'); } }; (例如,在计时器达到零之后),以显示没有给出答案?

现在,平均值计算显示3个给定(正确)的100%正确,然后2个未给出

// after test

var name = socket.userName; var room = socket.room; var created = testResults[room].created; var students = testResults[room].students; var problems = testResults[room].testProblems; var test = new tests({ roomId : room, created : created, teacher : name, students : students, problems : problems }); test.save(function(err, result) { if (err) {console.log(err);} else { console.log('test saved to DB'); socket.emit('testSaved'); // delete from roomList testRooms.deleteRoom(room, name); // delete from resultObject testResults.deleteRoom(room); // answer io.in(room).emit('room Closed'); } });

router.get('/showtests/:roomId', function(req, res) {
    if (req.user && req.user.role === 'teacher') {
        tests.findOne({roomId: req.params.roomId}, {}, function(err, result) {
            if (err) {console.log(err);}
            res.render('showSingleTest', {user: req.user, testData: JSON.parse(JSON.stringify(result))});
        })
    } else {
        res.render('customerror', { title: "Error", errMsg1: "error.error", errMsg2: "error.notLoggedIn" });
    }
});

从DB afterwars读取测试的路线

h2(data-i18n="markup.studentsAnswers")
each student in testData.students
    .testViewSingleStudentAnswers.col-md-6
        h3 #{student.studentName}

        ol.answers
            each answer in student.givenAnswers
                if (answer)
                    if (answer.correct == true)
                        li.correct
                            span #{answer.answer}
                            | &nbsp;&nbsp;&nbsp;
                            span.floatRight (#{answer.takenTime}s)
                    else
                        li.wrong
                            span #{answer.answer}
                            | &nbsp;&nbsp;&nbsp;
                            span.floatRight (#{answer.takenTime}s)
                else
                    li.noAnswer(data-i18n="markup.noAnswerGiven")
        .testTotals
            | #{student.avgCorrect}
            span(data-i18n="markup.percentCorrect")
            | ,&nbsp;
            | #{student.avgTime}
            span(data-i18n="markup.avgTime")

aaaaa和玉

{{1}}

3 个答案:

答案 0 :(得分:2)

你可以这样做:

function push_answer(answer){
answer = answer || "undefined"
array_of_answers.push(answer)
}

现在,该值未定义,但由文字定义。你可以用一些unicode字符替换它,以防某些答案可以是&#34; undefined&#34;。

度过美好的一天!

答案 1 :(得分:0)

似乎对我没有问题。

HTML:

<div id="content">

</div>   

JS:

var answers = ["answer1","answer2",undefined,"answer3",undefined];

for(i=0;i<answers.length;i++) {
  if(!answers[i]){
    answers[i]="no answer";
  }
}
document.getElementById('content').innerHTML = answers;

jsFiddle

答案 2 :(得分:0)

我的个人推荐:&#34;永远不要把事情弄清楚&#34;

如果学生没有选择答案,你应该用“&#39;”填充该空白区域,因为未定义真的很难处理,所以为了填补空白:

这将检查答案是否为&#34;未定义&#34;用&#39;填补空白(空白),然后,当你检查答案时,评估会更简单......

Sub taskupdateMacro(item As Outlook.MailItem)

 Dim olkApp, olkNS, olkTaskFolder, objItem, olkTaskUpdate, olkTask
 Dim objCount
 objCount = 0

 Set olkApp = CreateObject("Outlook.Application")
 Set olkNS = olkApp.GetNamespace("MAPI")
 olkNS.Logon "Outlook"
 Set olkTaskFolder = olkNS.GetDefaultFolder(6)
 For Each objItem In olkTaskFolder.Items
     If (objItem.Class = 50 Or objItem.Class = 51 Or objItem.Class = 43) Then
        objCount = objCount + 1
        objItem.Display
        objItem.Close 1
     End If
 Next

 If objCount = 0 Then
    MsgBox "No Task Related Emails to Open"
 End If

 Set objItem = Nothing
 Set olkTaskFolder = Nothing
 Set olkTaskRequest = Nothing
 Set olkTask = Nothing
 olkNS.Logoff
 Set olkNS = Nothing
 Set olkApp = Nothing

End Sub