[英]Compare key values from two arrays in js
I have two arrays, one is answers
and the other is correct
. 我有两个数组,一个是
answers
,另一个是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. 两者都完全相同,唯一的区别是
answers
来自用户输入,所以我想要做的是将这个数组与已经有解决方案的数组进行比较,这样我就可以给用户一个分数。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.