最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Checking item of array on "undefined" in JavaScript - Stack Overflow

programmeradmin4浏览0评论

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 paring 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).

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 paring 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).

Share Improve this question edited Feb 21, 2015 at 22:51 Prasad Silva 1,0422 gold badges11 silver badges30 bronze badges asked Feb 18, 2012 at 21:42 Eugene ShmorgunEugene Shmorgun 2,07512 gold badges42 silver badges69 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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

You can use indexOf method on array.

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

hasUndefined([1,2,3, undefined, 5]);
发布评论

评论列表(0)

  1. 暂无评论