javascript - 嵌套 IF-FOR-IF 循环

标签 javascript

我陷入了嵌套循环。 this.isRyt 是一个变量,用于存储从 JSON 检索的字符串。 i 是字符串类型的用户输入变量。 this.storeArray[] 是一个数组,仅当用户输入的 ithis.isRyt 中存储的字符串匹配时才会存储该数组所以基本上我想通过使用索引k将存储在this.storeArray[]中的字符串与存储在this.isRryt中的字符串进行比较(因为用户的多个 i 输入将存储在 this.storeArray[] 中的不同索引位置),如果字符串匹配,则有一个变量 counter 会递增。incCounter 只是一个用值 0 初始化的简单计数器变量。

我的尝试:我尝试使用下面的循环,但是 this.counter++ 在一次内多次递增(k 的多次迭代),因为它位于for 循环。我想让它只增加一次,但 for 条件不应被省略。

filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
      {


         this.isRyt = this.questArrayNew1[0].isRight;
         if(this.isRyt == i )
        {


           for(let k = 0 ; k < this.questArray.length ; k++)
            {

            if(this.storeArray[k] == i)
            {   
              console.log(k);
            }
            else
            {
              this.counter++; //WANT TO INCREMENT ONLY ONE TIME IF IT DOESNT SATISFY THE CONDITION FOR WHOLE K=0,1,2,3.. variable
            } 

           }

            this.storeArray[this.incCounter] = i ;
            console.log(this.storeArray);
            this.incCounter++;

        }
        else
        {
          return 0;
        }

      }

最佳答案

如果我理解正确的话, this.counter 只需要增加一次。你可以尝试这样的事情:

filterAnswer(i:any) //Comparing Answer submitted by user with JSON answer
  {
     var notCounted = true; //condition for this.counter++ code block to be executed
     this.isRyt = this.questArrayNew1[0].isRight;

     if(this.isRyt == i )
      {

       for(let k = 0 ; k < this.questArray.length ; k++)
        {
          if(this.storeArray[k] == i)
           {   
             console.log(k);
           }
        else
           {
             while(notCounted)
              { //executes while bool is true
               this.counter++; 
               notCounted = false; //incremented so now no longer needed
              }
           } 
        }

        this.storeArray[this.incCounter] = i ;
        console.log(this.storeArray);
        this.incCounter++;

    }
    else
     {
      return 0;
     }

  }

关于javascript - 嵌套 IF-FOR-IF 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024808/

相关文章:

javascript - 通过按钮按下相同的随机图像

javascript - 当我尝试将 React-router v5 升级到 V6 时出现错误

javascript - 注销后出现缺少或权限不足的错误

javascript - 有没有办法用 JavaScript/CSS 制作 3D 文本效果

javascript - 为计时器添加开始、停止、重置按钮

javascript - 为同一对象中的另一个值获取 JSON 对象值

javascript - 使用 phantomJS 运行源的 javascript

javascript - 更改标签 Chart.js 的背景颜色

javascript - 动态打开的下拉菜单

javascript - meteor .js : how to pass the data context of one helper to another helper?