Mantas Vidutis
Mantas Vidutis

Reputation: 16804

Javascript If Statement not Evaluating True

I am attempting to catch the last case in a forEach loop, but all cases seem to evaluate to false instead of the last one being true. My code:

for(var i in networks){
    if (i == (networks.length - 1)){
        //do stuff
    }
}

What is going wrong?

Upvotes: 2

Views: 329

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163318

Try this:

for(var i = 0, j = networks.length; i < j; i++){
    if (i == (j - 1)){
        //do stuff
    }
}

I personally despise the for...in loop in JavaScript because it brings into the picture a whole bunch of unwanted properties, it's unreliable - needs a ton of sanity checks to make sure the current property is not of an unwanted type or undefined. I can go on and on about this. I suggest that the only time that you ever think of using it is when you are iterating over objects and you need key values.

Upvotes: 4

Samantha Branham
Samantha Branham

Reputation: 7451

If networks is an array of numbers in order from 0 to n, that should work. ;) If it's not, you might want to consider a standard for loop:

for(var i = 0; i < networks.length; i++) {
    var network = networks[i]; // in case you need this.
    if (i == (networks.length - 1)){
        //do stuff
    }
}

Upvotes: 1

Related Questions