当前位置: 动力学知识库 > 问答 > 编程问答 >

How to traverse an object in Javascript in loop which is not linear

问题描述:

I have an object with structure as below:

group[0] = [Object {code: 1}, {code: 2}, {... and so on}]

group[1] = [Object {code: 3}, {code: 4}, {... and so on}]

group[2] = [Object {code: 3}, {code: 4}, {... and so on}]

group[3] = [Object {code: 3}, {code: 4}, {... and so on}]

group[4] = [Object {code: 3}, {code: 4}, {... and so on}]

In case 1: My group.length gives me 5 and I can traverse as

for(i=0;i<group.length; i++) {}

But if I delete any particular entry say the second one then the structure becomes as

group[0] = [Object {code: 1}, {code: 2}, {... and so on}]

group[2] = [Object {code: 3}, {code: 4}, {... and so on}]

group[3] = [Object {code: 3}, {code: 4}, {... and so on}]

group[4] = [Object {code: 3}, {code: 4}, {... and so on}]

Because of some limitation I can't change the number of other groups and now my group.length is 4 so if I put a for loop it gives error for group[1] case as it becomes undefined.

Please give me a solution so that i can bypass the undefined values

网友答案:

The problem is that group.length is being re-evaluated when you remove an element from the array. Do this:

group_length = group.length
for(i=0;i<group_length; i++) {}

Edit: This assumes that you are deleting elements in the array from within the loop. If not, then disregard.

网友答案:

The issue is probably how you're deleting the entry. Try using the splice command instead, so group.splice(x, 1) where x is the element you want to remove.

Then group.length will adjust to the new size of the array.

EDIT: So, taking into account the feedback in the comment, how about something along the lines of

for(i=0;i<group.length; i++) {
  if(!group[i]) {
    continue;
  }
  //do stuff here
}
网友答案:

Guys I Finally had to add a counter and solve it without removing my entries. Thanks for all help

网友答案:

One possible solution,

for(i in group){  // i will return only valid indexes.
    console.log(group[i]);
}

JSFiddle

分享给朋友:
您可能感兴趣的文章:
随机阅读: