gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:47:21 26 4
gpt4 key购买 nike

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

例如

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com