-3

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 ;

  }
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
user1595858
  • 3,700
  • 15
  • 66
  • 109
  • 3
    Don't do that; use regular for loops. – SLaks Jan 29 '15 at 21:42
  • 1
    Maybe you can use a loop like this instead: `for(var i = 0; i < list.length; i++)`. – GolezTrol Jan 29 '15 at 21:42
  • 1
    Is `list` an array of an object? if it's an array, don't use `for...in`. A regular `for` loop should be sufficient. Otherwise `hasOwnProperty` should help. – Matt Burland Jan 29 '15 at 21:42
  • 1
    http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea and also see [`for..in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) and [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) – Xotic750 Jan 29 '15 at 21:47
  • always use a hasOwnProprerty() filter when using for-in loops. – dandavis Jan 29 '15 at 21:57

1 Answers1

2

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
}
Matt Burland
  • 44,552
  • 18
  • 99
  • 171