mardi 24 janvier 2017

For loop with if statement will not run more than once javascript

Apologies for the probably exceedingly simple question; I have just started using Javascript.

I am trying to print the odd and even numbers from an array but for some reason my loop is being exited after only printing one number ("0 is even" is being printed). I don't understand why it doesn't iterate through 1,2,3,4,5 and 6 as well?

<!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>

Aucun commentaire:

Enregistrer un commentaire