Javascript: is it safe to delete properties for an object that is executed using 'for'

I am 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 fine in the samples I tried, but I'm not sure if this can lead to unexpected behavior in certain scripts / browsers.

Is it possible to change a repeating object?

+6
source share
2 answers

Section 12.6.4 explains that for..in is defined in terms of the following property:

Let P be the name of the next obj property whose [[Enumerable]] attribute is true. If there is no such property, return (normal, V, empty).

Since the concept of β€œnext property” is well defined even if there is a mutation (although the iterative order is not), delete does not introduce undefined behavior during iteration.

There is an angular case where delete does not mask the 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 can iterate y and delete x , you should still see x from the prototype, but if you repeated x first and then y , you should not see the second x .

+8
source

Yes, it is safe.

http://es5.github.com/#x12.6.4

12.6.4 in-in statement

The mechanics and order of listing properties (step 6.a in the first algorithm, step 7.a in the second) is not indicated. The properties of an enumerated object can be deleted during 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, newly added properties are not guaranteed to be visited in the active enumeration. The property name must not be visited more than once in any enumeration.

+6
source

Source: https://habr.com/ru/post/920065/


All Articles