简体   繁体   中英

JavaScript looping through an object while adding items

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM