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..in
is defined in terms of the "next property":
Let P be the name of the next property of obj whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V, empty).
Since the concept "next property" is well defined even in the presence of mutation (though iteration order is not), delete
during iteration does not introduce undefined behavior.
There is a corner case where delete
un-masks a prototype property as in
var obj = Object.create({ x: 1 });
obj.y = 2;
obj.x = 3;
for (var k in obj) {
if (k == 'y') { delete obj.x; }
alert(k);
}
In this case, where you might iterate y
and delete x
, you should still see the x
from the prototype, but if you iterated x
first, then y
you should not see the second x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With