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?

2
  • Is your index numeric (0, 1, 2, etc.) or is it something else like "bob", "cat", "dog", "foo" ? Commented Jun 22, 2010 at 19:14
  • My index is numeric, when I print out i it goes from 0 to (n - 1) Commented Jun 22, 2010 at 19:16

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+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.
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.
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.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.