我有两个数组,一个包含正确答案的索引号 correctAnswers
而userAnswers
包含用户选择的答案的索引号
我如何检查它们在索引上是否具有相同的值,如果是,则将 +1 添加到 Total
this.state = {
correctAnswers: [], // [1, 2, 3, 1, 2, 1, 3, 3, 4, 3]
userAnswers: [], // [1, 3, 1, 2, 2, 1, 1, 3, 4, 3]
Total: 0
};
所以在上面的例子中 Total 应该是 Total =6
我的尝试:
const correctAnswers = this.state.correctAnswers;
const userAnswers = this.state.userAnswers;
compareAnswers() {
for (var i = 0; i < correctAnswers.length; i++) {
if (correctAnswers[i] === userAnswers[i]) {
this.setState({ Total: +1 });
} else console.log("ITS NOT A RIGHT ANSWER ");
}
}
最佳答案
好的,因为它是一个对象内部的数组,并且实际对象有一个 this
引用,我们必须适应它。
for(var i=0;i<this.state.correctAnswers.length;i++){
if(this.state.correctAnswers[i] === this.state.userAnswers[i]){
this.state.Total++;
}
}
使用这种方法,我们可以动态地比较两个数组。希望这对您有所帮助!
关于javascript - 如何检查 this.state 中的两个数组是否包含相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061552/