I’m doing something like this:
var myObj = {a:1, b:2, c:3, d:4};
for (var key in myObj){
if (someCondition){
delete(myObj[key]);
}
}
It works just fine in the samples I’ve tried, but I’m not sure if it might have an unexpected behavior in certain scenarios/browsers.
Is it ok to modify the object being iterated?
Section 12.6.4 explains that
for..inis defined in terms of the “next property”:Since the concept “next property” is well defined even in the presence of mutation (though iteration order is not),
deleteduring iteration does not introduce undefined behavior.There is a corner case where
deleteun-masks a prototype property as inIn this case, where you might iterate
yand deletex, you should still see thexfrom the prototype, but if you iteratedxfirst, thenyyou should not see the secondx.