javascript - Is it safe to modify an Object inside for (..in..) loop? -


a = { 1:1, 2:2, 3:3, 4:4, 5:5 }; (var in a) {     console.log(i);     if (a[i] == 4) delete a[i], a[7] = 7;     if (a[i] == 2) delete a[i], a[0] = 0;     if (a[i] == 7) console.log('seven');     if (a[i] == 0) console.log('zero'); } console.log(a); 

this seems work, not know details of implementation of for(..in..) loop sure safe in conditions.

see here same question arrays.

according mdn reference should not try this

if property modified in 1 iteration , visited @ later time, value in loop value @ later time.

a property deleted before has been visited not visited later.

properties added object on iteration occurring may either visited or omitted iteration.

in general best not add, modify or remove properties object during iteration, other property being visited.

there no guarantee whether or not added property visited, whether modified property (other current one) visited before or after modified, or whether deleted property visited before deleted.

so while might have worked in tests far might not always.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -