views:

39

answers:

2

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?

A: 

That is similar to a foreach in C#

Only going to loop 3 times for the number of properties in the object. Not going to be able to do it with for(var i in obj)

Alexander
+2  A: 

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.

Daniel Vassallo
+1 Nice find...
Alexander
Okay, I guess that's not going to work. However, adding properties during a loop would save a lot of coding.
Azmisov