javascript - 如何检查同一索引处的两个数组?

标签 javascript arrays reactjs

我想确定这两个数组中有多少项匹配,然后将其作为数字存储在状态中。

例如

const [score, setScore] = React.useState(0)

const selections = ["one", "two", "three"]
const allCorrectAnswers = ["four", "two", "three"]
// this should return 2

我试过了

function checkSelectedAnswer(selections, allCorrectAnswers) {
  selections.map(eachChoice =>
    eachChoice === allCorrectAnswers.map(eachAnswer => eachAnswer) 
      ? setScore(prevScore => prevScore + 1) : 0
  )
}

如果可以,请解释为什么我的代码不能正常工作。

最佳答案

.map(在顶层或嵌套的)没有意义,因为您不是要将一个数组的每个元素转换为另一个数组。如果要使用数组方法,请改用 .reduce,并使用回调中的索引访问另一个数组中的关联元素,看是否相等。

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];
const totalCorrect = selections.reduce(
  (correctSoFar, answer, i) => correctSoFar + (answer === allCorrectAnswers[i]),
  0
);
console.log(totalCorrect);
// setScore(totalCorrect);

或者做

const selections = ["one", "two", "three"];
const allCorrectAnswers = ["four", "two", "three"];

let totalCorrect = 0;
selections.forEach((answer, i) => {
  if (answer === allCorrectAnswers[i]) {
    totalCorrect++;
  }
});
console.log(totalCorrect);
// setScore(totalCorrect);

关于javascript - 如何检查同一索引处的两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71024334/

相关文章:

javascript - 在 React Native 中创建一个简单的标签格式化程序

javascript - 通过 jQuery 定位表的偶数行

java - 构建一个仅打印基于文件的数组的特定部分的方法

javascript - 如何在 AngularJS 中保存对象的 JSON 索引位置,而不是对象本身?

c - 打印一个字符数组(C)只有第一个字母

javascript - 在 reducer 中向 redux store 添加功能是一种反模式?

javascript - 重新应用运行示例厨房水槽应用程序时出错

javascript - Firebase 是否缓存数据?

javascript - 如何创建一个出现在点击菜单项上的框?

javascript - getNodeById 不起作用