(编码JS(
我正在尝试编写一个修正程序,应用于某种多选测验中——有3个可能的答案(a、B、C(
我显然需要变量(名称(
var Simon = [A, B, C, A, B, C, A, B, C]
var (new name) = [.., ..., ..., .. and so on]
以及某种正确的字符串:[A, B, B, B, C, A , B, C]
现在,如果我例如
console.log(functionName([A, B, B, A, B, C, C, A, B])
我希望输出是这样的:;Simon";因为他有最正确的答案(5个正确(,所以函数必须检查并匹配每个名称/变量的索引。
我不久前开始编码,所以我有点新(noob(。也许我已经受够了这种挑战。。。
提前感谢!
您可以编写一个函数,为数组中的每个元素执行该函数(例如Simon(。然后,此函数应该将该数组的当前元素(Simon(与正确答案进行比较。这可能是这样的:
var simon = ["A", "C", "B", "D"];
var correctAnswers = ["A", "B", "C", "D"];
var simonsScore = 0;
// This executes the fuction checkCorrectAnswers for each element in Simon
simon.forEach(checkCorrectAnswers);
alert("Correct Answers: " + simonsScore);
// item is the current item and index is its index
function checkCorrectAnswers(item, index) {
// Compare the answer with the correct answer
if(item == correctAnswers[index]) {
// if they are correct, increase simonsScore
simonsScore++;
}
}
编辑:
好吧,如果你;只是";需要学生的名字,然后你得到一个二维数组。第一级阵列是";列表";在所有学生中。第二个层次是学生用他们的";数据";。数据是他们的名字、答案和分数。所以你可以像我们上面做的一样(使用forEach来遍历数组(,但你需要在两个级别上都这样做。
下面的代码记录了得分最高的学生的名字和他们的分数。
这对你有用吗?
var answers = [["Simon", "A", "C", "B", "D"], ["Bob", "A", "B", "E", "D"]];
var correctAnswers = ["correctAnswers", "A", "B", "C", "D"];
var highestScore = 0;
var highestScoreName = "";
// This executes the fuction checkCorrectAnswers for each element in answers
answers.forEach(compareStudents);
// Log your result
console.log("Most Answers are " + highestScore + " by " + highestScoreName);
// Function ---------------------------------------------------
function compareStudents (item, index, arr) {
// First we create a score variable for each student an push it in their array
var score = 0;
arr[index].push(score);
// Now we check answers for each Student
arr[index].forEach(checkCorrectAnswers);
// Now their score has been updated in checkCorrectAnswers,
// so now we can check if their score is higher than the highest score
// to get the last element of the array thats the current student
var score = arr[index][arr[index].length-1];
// and compare it with the highscore
if(score > highestScore) {
highestScore = score;
highestScoreName = arr[index][0]; // thats where we find the name of the student
}
}
// item is the current item and index is its index, arr is the array we're checking
function checkCorrectAnswers(item, index, arr) {
// get the current score from the array with is the last element and save it
var score = arr[arr.length-1];
arr.pop();
// compare the answwer with the correct one
// (the first element compared will be their name compared with "correctAnswers", which will never be true)
if(item == correctAnswers[index]) {
score++;
console.log("Correct answer: " +item + " = " + correctAnswers[index] + ". Total of " + score + " correct answers.");
}
// Push the score into the array, so the last element is always the score
arr.push(score);
}