【发布时间】:2017-01-24 15:51:12
【问题描述】:
我正在尝试打印数组中的奇数和偶数,但由于某种原因,我的循环在仅打印一个数字后退出(正在打印“0 是偶数”)。我不明白为什么它也不遍历 1、2、3、4、5 和 6?
<!DOCTYPE html>
<html>
<body>
<p> Click the button to print odd and even numbers </p>
<button onclick="loopNum()">Click me</button>
<p id="loopNumbers"></p>
<script>
function loopNum(){
var numbers = [1, 2, 3, 4, 5, 6]
var text;
for(var i = 0;i < numbers.length;i++){
if (i % 2 ==0){
text = (i += " is even");
}
else if (i % 2 !=0){
text = (i += "is odd");
}
document.getElementById("loopNumbers").innerHTML=text;
}
}
</script>
</body>
</html>
【问题讨论】:
-
我虽然没有人会犯这个错误......不要在你的循环中使用
i +=。这是邪恶的。 -
你把
i变成了一个字符串。
标签: javascript if-statement for-loop