需要为单个阵列添加多个答案

时间:2014-04-22 13:19:58

标签: javascript

我需要添加多个问卷以使用相同的代码/数组。我怎么能这样做?

// Insert answers to questions
answers[0] = ["Apple", "Test"] ;
answers[1] = "Dynamic HTML";
answers[2] = "Netscape";
answers[3] = "Common Gateway Interface";

正如您所看到的,我刚尝试将其他答案添加到代码数组中以进行不同的测验,但它无法识别答案(测试)。这样做的最佳方式是什么? (是否有“或”命令或类似的东西?

以下是我的全部代码:

// Insert number of questions
var numQues = 4;

// Insert number of choices in each question
var numChoi = 3;

// Insert number of questions displayed in answer area
var answers = new Array(4);


// Insert answers to questions
answers[0] = ["Apple", "Test"] ;
answers[1] = "Dynamic HTML", "Test";
answers[2] = "Netscape",  "Test";
answers[3] = "Common Gateway Interface", "Test";

// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
  currSelection = form.elements[currElt + j];
  if (currSelection.checked) {
    if (currSelection.value == answers[i]) {
      score++;
      break;
    }
  }
 }
}
score = Math.round(score/numQues*100);
form.percentage.value = score + "%";
var correctAnswers = "";
for (i=1; i<=numQues; i++) {
correctAnswers += i + ". " + answers[i-1] + "\r\n";
}
form.solutions.value = correctAnswers;
} 
//  End -->

所以只是为了让它更容易理解..我希望有一些不同的测验链接到这个代码用于答案而不是重复每个测验的整个代码。需要做哪些修改?

1 个答案:

答案 0 :(得分:0)

如果你希望你的答案数组是一个数组数组,你应该在1,2和3行周围有[]吗?

喜欢这个......

answers[0] = ["Apple", "Test"] ;
answers[1] = ["Dynamic HTML", "Test"];
answers[2] = ["Netscape", "Test"];
answers[3] = ["Common Gateway Interface", "Test"];

如果我可以在该行下方编辑,请求我不要这样做,这可能更容易帮助。我想你真的想要像

这样的东西
currSelection.value == answers[i][j]

而不是

currSelection.value == answers[i]