Javascript - Continue statement not working?

4.9k views Asked by At

Im currently learning about break and continue statements. It prints the 1st array, the 2nd array runs the alert like it suppose to, but the third one doesn't run, when i use the continue statement. Maybe im not doing it right? some guidance for a newbie would be nice.

Im using JSBin to run this.

p.s. im learning from the "Begining Javascript" book

Thanks

var n = [233, "john", 432];
var nIndex;

for (nIndex in n) {
    if (isNaN(n[nIndex])) {
        alert(n[nIndex] + " is not a number");
        continue;
    }
    document.write(n[nIndex] + " ");
}

2

There are 2 answers

0
Michael Laszlo On

This is how you iterate over the elements of an array:

var data = [233, "john", 432];

for (var i = 0; i < data.length; ++i) {
    if (isNaN(data[i])) {
        alert(data[i] + " is not a number");
        continue;
    }
    document.write(data[i] + " ");
}

By the way, you can remove the continue statement and instead use else on the alternate instructions:

    var data = [233, "john", 432];

    for (var i = 0; i < data.length; ++i) {
        if (isNaN(data[i])) {
            alert(data[i] + " is not a number");
        } else {
            document.write(data[i] + " ");
        }
    }

That's logically equivalent and you may find it easier to read.

0
Dattatray Walunj On

Continue does not work in :

for(i in  array) {}

it works for for(i=0; i<n; i++){}