Is it safe to delete an object property while iterating over them?

When repeating over object properties, is it safe to delete them during the in-in cycle?

For example:

for (var key in obj) { if (!obj.hasOwnProperty(key)) continue; if (shouldDelete(obj[key])) { delete obj[key]; } } 

In many other languages, iterating over an array or dictionary and deleting inside is unsafe. Is this normal in JS?

(I use the Mozilla Spidermonkey runtime.)

+79
javascript object loops properties
Aug 11 '10 at 21:37
source share
2 answers

ECMAScript 5.1 , section 12.6.4 (for in-in loops) says:

The properties of an enumerated object can be deleted during enumeration. If property that has not yet been visited during the transfer is deleted, then it is not visited. If new properties are added to the object being enumerated during the enumeration, newly added properties are not guaranteed to be visited in the active enumeration. The property name should not be visited more than once in any enumeration.

Therefore, I think it is clear that the OP code is legal and will work as expected. Browser privileges affect the iteration order and generally delete statements, but does the OP code not work? It is usually best to remove the current property in an iteration - deleting other properties of the object will unpredictably lead to their inclusion (if it has already been visited) or not to be included in the iteration, although this may or may not be a problem depending on the situation.

See also:

However, this does not affect the OP code.

+86
Oct 24 '13 at 11:29
source share

From the Javascript / ECMAScript specification (specifically 12.6.4 in-in statement ):

The properties of an enumerated object can be deleted during an enumeration . If a property that has not yet been visited during the enumeration is deleted, then it will not be visited. If new properties are added to the object that is being enumerated during the enumeration, the added properties are not guaranteed to be visited in the active enumeration. Property names cannot be visited more than once in any enumeration.

+15
Oct 23 '13 at 23:05
source share



All Articles