2

My file works just fine in the first round of loop when i try to rerun the function again. It shows the previous value of the previous loop when i try to use the value to match and after which it shows the correct value. If i run the function again and again, it keeps holding on to the value of the previous generated random value.

for (var i=0; i<9; i++)
  {
    var ranD = Math.floor(Math.random()*33);

    if (mathStar.indexOf(ranD)== -1) {
     mathStar.push(ranD);
     item[i].innerHTML = mathStar[i];
      }
      else {
        i--;
      }
      itemVal[i].value = mathStar[i];

  }
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • What is the purpose and expected result of `i--`? – guest271314 Feb 08 '19 at 06:52
  • i-- , so that the generated number does not have duplicates . – thefirstlove Feb 08 '19 at 06:54
  • The final expression of the `for` statement is `i++`. The code could lead to an infinite loop. How does `i--` prevent duplicate numbers from being printed? – guest271314 Feb 08 '19 at 06:56
  • See [Random number, which is not equal to the previous number](https://stackoverflow.com/q/40056297/); [run for random numbers and keep state](https://stackoverflow.com/questions/41001101/) – guest271314 Feb 08 '19 at 07:09

2 Answers2

1

Substitute using const and let for var within for loop to avoid creating global variables and --i could have unexpected results within the code where i++ is also used in the foor loop.

guest271314
  • 1
  • 15
  • 104
  • 177
0

Is this the first occurrence of "mathStar"?

If this is the first place you're using mathStar, it means it gets created globally and that usually leads to confusion. In this case, take a look at this.

Looking at just this, it seems that you are not resetting your "mathStar" value. This way, any time you run this loop for the nth time, the values you have added to "mathStar" using mathStar.push(...) also occur in the list of values.

saglamcem
  • 677
  • 1
  • 8
  • 15
  • is there a code to add on so that it will always reset the mathStar Value? – thefirstlove Feb 08 '19 at 06:53
  • @thefirstlove If you say "const mathStar" (or "let mathStar" depending on your need) instead of just "mathStar", and initialize it with a value (const mathStar = [] or so), you would be certain that the mathStar value is resetted. TL;DR Use const/let when initializing your values, and set an initial value (for instance an empty array []). When this function is called again, mathStar will be created again with the value that you set initially ([] in the above case). – saglamcem Feb 08 '19 at 08:20