javascript - 如何检查 this.state 中的两个数组是否包含相同的值?

标签 javascript reactjs

我有两个数组,一个包含正确答案的索引号 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/

相关文章:

CSS 模块导入未将 css 应用于 "react-scripts": "2.0.4" 的 html

javascript - Ember : Loading all template at once

javascript - HTML5 canvas 基于滚动的动画吸引和脱离

node.js - react 样板 npm 安装错误

reactjs - React Native - 为什么我需要 babel 或 webpack?

javascript - 在 React 内联样式中使用 props 作为关键属性

javascript - MIME 类型 ('text/html' ) 不是受支持的样式表 MIME 类型

javascript - 如何检查 Jest 中异步抛出的错误类型?

javascript - 访问 View 模型中的对象 Knockout

javascript - 为什么这个网站使用 html5 pushstate 对 seo 不友好?