3

My JS-code has array arrayResults, some element of him can be "undefined" - this is feature of algorithm. To check that there is no such elements I use the follow code:

for (i in arrayResults)
        {
          if (typeof(arrayResults[i])=='undefined')
           {
              // ask user to repeat
           };
        };  

But, using the debugger, I found that JS-engine passes the "undefined"-item of array (in for condition), respectively I don't have the possibility to make the comparing and make the follow instructions.

So, is there any way to really check the "undefined" items in array? (I can't to set items of array in sequence, because if I found the position of "undefined" item, I tell to user to go to this position).

Prasad Silva
  • 1,020
  • 2
  • 11
  • 28
Eugene Shmorgun
  • 2,083
  • 12
  • 42
  • 67

2 Answers2

9

Don't use a for..in loop to iterate arrays. If you are interested in the reasons, please read this StackOverflow question. They should only be used for traversing objects.

Use a simple oldschool for loop instead, it will solve your problem.

for (var i = 0, l = arrayResults.length; i < l; i++) {
    if (typeof(arrayResults[i])=='undefined') {
         // ask user to repeat
    };
};  

jsFiddle Demo

Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
  • 1
    +1 Here the old-school for loop is superior to all the higher-order functions like `.some()` or `.reduce()` or even `.indexOf()` because the array methods skip so-called "holes", elements that are "undefined" because they were never set. – Paul Mar 15 '17 at 04:08
4

You can use indexOf method on array.

function hasUndefined(a) {
    return a.indexOf() !== -1;
}

hasUndefined([1,2,3, undefined, 5]);
Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37