我想确定这两个数组中有多少项匹配,然后将其作为数字存储在状态中。
例如
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/