Is It Safe To Modify An Object Inside For (..in..) Loop?
Solution 1:
According the MDN reference you should not try to do this
If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time.
A property that is deleted before it has been visited will not be visited later.
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 (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.
So while it might have worked in your tests so far it might not always.
Solution 2:
By using that method you could potentially skip over indexes of A
because as you delete elements, the indexes of all other elements will shift by -1 and may then by missed by the iterator. Instead, you could create a second list and then only add the good values from A
to it.
Post a Comment for "Is It Safe To Modify An Object Inside For (..in..) Loop?"