我遇到一个问题,即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");
}
}
非常感谢你的帮助:))
答案 0 :(得分:1)
您的代码正在成为The Horror of Implicit Globals的牺牲品,因为您尚未声明i
。我猜测你没有显示的函数Kreis
也使用全局i
。因此,当您第一次致电Kreis
时,您会更改i
的值,使其高于循环限制。
示例:
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;
道德:声明你的变量:
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;
答案 1 :(得分:0)
使用let
关键字。
您使用i
作为global
变量。这可能会杀死你的循环。
或者您也可以使用var
。
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");
}
}