Javascript for循环只执行一次代码

时间:2015-10-31 09:31:29

标签: javascript

我遇到一个问题,即for循环只执行一次代码而不是给定的次数。

如果我在文本字段中放入了不是数字的内容,我会收到错误,console.log()会显示我放在文本框中的数字。

它执行的代码无关紧要,我也试过了。

代码:

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");
    }
}

非常感谢你的帮助:))

2 个答案:

答案 0 :(得分:1)

您的代码正在成为The Horror of Implicit Globals的牺牲品,因为您尚未声明i。我猜测你没有显示的函数Kreis 使用全局i。因此,当您第一次致电Kreis时,您会更改i的值,使其高于循环限制。

示例:

&#13;
&#13;
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();
&#13;
<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>
&#13;
&#13;
&#13;

道德:声明你的变量:

&#13;
&#13;
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();
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用let关键字。 您使用i作为global变量。这可能会杀死你的循环。 或者您也可以使用varlet 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");
    }
}

let关键字的浏览器兼容性。 enter image description here