javascriptenyo

best way to use "for in"


The code which worked before was failing now in for loop after I added enyo.js. I suspect that when I use for(var ls in list) it loops through even when length is 0. When I put the debugged I found out that it is considering "findIndex" as one of value in list and goes into the loop. I have several places using for with in, I want to find out a best way to filter out "findIndex" or any invalid indexes so that only valid elements go into the loop

for(var ls in list)
  {
    var lin = list[ls].rb ;

  }

Solution

  • If you list is an array, just use a regular for loop. It's generally not a great idea to use for...in with an array for exactly this reason and also because the order isn't guaranteed.

    If you must use for...in use a hasOwnProperty check:

    for (var ls in list)
    {
       if (list.hasOwnProperty(ls)) {
           var lin = list[ls].rb;
           // ...
       }
    }
    

    Of course, if you only concern is whether you have an rb property, you could just test for that:

    if (list[ls].rb) {
        var lin = list[ls].rb;
    }
    

    Or even:

    var lin = list[ls].rb;
    if (lin) {
        // do whatever you needed to do with lin
    }