I have two arrays, one is answers
and the other is correct
. Both are exactly the same, the only difference is that the answers
fills from the user input, so what I want to do is compare this array with the array that already has the solutions so I can give back to the user a score.
I did this function to compare them:
const correct = [{ slot1: "item1", slot2: "item2", slot3: "item3", slot4: "item4", slot5: "item5", slot6: "item6", slot7: "item7", slot8: "item8" }]; var answers = { slot1: "", slot2: "", slot3: "", slot4: "", slot5: "", slot6: "", slot7: "", slot8: "" }; function outputTest(){ //console.log(answers); compare(); } function compare(){ for (var[key, value] of Object.entries(correct)){ console.log(answers[key]); console.log(correct[key]); if (correct[key] == answers[key]){ score += 1; } } console.log("total score= "+score); } outputTest();
But it seems like it doesn't get "answers" array, it shows "undefined", even tho I tested it and it inserts the values correctly before. Is this the right way to achieve this?
const correct = [{ slot1: "item1", slot2: "item2", slot3: "item3", slot4: "item4", slot5: "item5", slot6: "item6", slot7: "item7", slot8: "item8" }]; var answers = { slot1: "", slot2: "item2", slot3: "", slot4: "", slot5: "", slot6: "item6", slot7: "item7", slot8: "" }; function outputTest() { compare(); } function compare() { var total = Object.keys(answers).reduce(function(total, answerKey) { if (answers[answerKey] === correct[0][answerKey]) { total++; } return total; }, 0); console.log("total score = " + total); } outputTest();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.