2

When i try:

for (index = 0; index < results[1].length; ++index) {
          results[1].splice(index,0,{Keys:"Test"}); 
}

the code crashes - it adds more element to an array and the loop is going endless

1
  • "the code crashes" with which error? Modifying the array while iterating over it usually causes problems (unless done right). Commented Jan 11, 2018 at 10:27

1 Answer 1

1

the code crashes - it adds more element to an array and the loop is going endless

Because index < results[1].length never fails as you keep on increasing the length of result by adding elements to it.

make it

var length = results[1].length;
for (index = 0; index < length; ++index) {
    results[1].splice( index, 0, {Keys:"Test"} ); 
}

Also, this will keep pointing the index to the newly added item, so increase the index as well

for (index = 0; index < results[1].length; index = index + 2) 
{
    results[1].splice( index, 0, {Keys:"Test"} ); 
}
Sign up to request clarification or add additional context in comments.

7 Comments

This will not iterate over the last N element where N is the number of newly inserted item, isn't it?
The second one will not iterate over all original elements either.
OP hasn't mentioned about iterate over last N element. What did I missed?
@gurvinder372: That would require to update length as well. Or keep index < results[1].length;.
@FelixKling Yes, I missed that part. Thanks for pointing it out.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.