-2

I have a problem that a for-loop executes its code just one time instead of the given number times.

If I put something thats not a number into the textfield I get the Error and console.log() shows me the number I put in the textbox.

It doesnt matter what code it would execute, I tried that aswell.

Code:

function Mehrere() {

    var Anzahl = document.getElementById("Anzahl").value;
    var AnzahlInt = parseInt(Anzahl);
    console.log(AnzahlInt);

    if (AnzahlInt > 0) {
        for (i = 0; i < AnzahlInt; i++) {
            Kreis();
        }
    } else {
        alert("Error");
    }
}

Thank you very much for your help :)

DoodleSchrank
  • 43
  • 1
  • 6

2 Answers2

1

Your code is falling prey to The Horror of Implicit Globals because you haven't declared i. I'm guessing that the function Kreis, which you haven't shown, also uses a global i. So when you call Kreis the first time, you change the value of i so it's higher than the loop limit.

Example:

function Mehrere() {

    var Anzahl = document.getElementById("Anzahl").value;
    var AnzahlInt = parseInt(Anzahl);
    console.log(AnzahlInt);

    if (AnzahlInt > 0) {
        for (i = 0; i < AnzahlInt; i++) {
            Kreis();
        }
    } else {
        alert("Error");
    }
}
function Kreis() {
  snippet.log("In Kreis, changing i to 20");
  i = 20;
}
Mehrere();
<input type="text" id="Anzahl" value="10">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Moral: Declare your variables:

function Mehrere() {
    var i;                   // <==============================

    var Anzahl = document.getElementById("Anzahl").value;
    var AnzahlInt = parseInt(Anzahl);
    console.log(AnzahlInt);

    if (AnzahlInt > 0) {
        for (i = 0; i < AnzahlInt; i++) {
            Kreis();
        }
    } else {
        alert("Error");
    }
}
function Kreis() {
  snippet.log("In Kreis, changing i to 20");
  i = 20;
}
Mehrere();
<input type="text" id="Anzahl" value="10">
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Use let keyword. You are using i as global variable. which might be killing your loop. or you can use var also. let reference

function Mehrere() {

    var Anzahl = document.getElementById("Anzahl").value;
    var AnzahlInt = parseInt(Anzahl);
    console.log(AnzahlInt);

    if (AnzahlInt > 0) {
        for (var i = 0; i < AnzahlInt; i++) {
            Kreis();
        }
    } else {
        alert("Error");
    }
}

Browser compatibility of let keyword. enter image description here

Kaushik
  • 2,072
  • 1
  • 23
  • 31