1

I have the following code segment:

var run = 0;
var obj = {'item1':0,'item2':5,'item3':10};
for (var i in obj){
    run++
    obj['newItem'+run] = 5;
}
return run;

and it returns 3. But I want it to go on infinitely and eventually crash the browser. Is there any way of updating the obj variable while in a for loop?

1
  • "But I want it to go on infinitely and eventually crash the browser". Even got an upvote :) Commented Aug 11, 2010 at 3:58

1 Answer 1

4

In general, you shouldn't be adding properties to objects over which an iteration is occurring.

Quoting the Mozilla Dev Center:

Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited; there is no guarantee whether or not an added property will be visited, whether a modified property will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, I guess that's not going to work. However, adding properties during a loop would save a lot of coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.