比较js中的两个数组的键值

时间:2019-05-21 15:30:54

标签: javascript jquery arrays

我有两个数组,一个是answers,另一个是correct。 两者完全相同,唯一的不同是answers由用户输入填充,所以我想做的就是将此数组与已经有解决方案的数组进行比较,以便我可以给用户一个得分。

我做了这个功能来比较它们:

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();

但是似乎它没有得到“答案”数组,它显示为“未定义”,即使经过我的测试,它也可以正确地插入值。 这是实现此目标的正确方法吗?

1 个答案:

答案 0 :(得分:0)

  • 获取所有答案的键并对其进行归约,初始总和为零。
  • 如果答案中的键与正确数组中对象的键匹配,则增加总数

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();