开发者

Javascript If Statement not Evaluating True

开发者 https://www.devze.com 2023-01-04 21:16 出处:网络
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:

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?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消