views:

73

answers:

2

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?

+4  A: 

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.

Jacob Relkin
+1 - the syntactic sugar of the "for ... in" syntax quickly loses its luster if you need to know where in the loop you are relative to the beginning/end.
inkedmn
Peculiar. Why is it that this works but using the index from a `for in` does not work? I would have liked to use the `for in` for readability, but if this is the only way it works, so be it.
mvid
Please note that 'for in' will iterate through each object and return the key in the associative array, whether it's an integer, string, etc. One reason it could have failed is 'networks' doesn't use integers for the keys.
SimpleCoder
Python, you have spoiled me.
mvid
+1  A: 

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
    }
}
Stuart Branham