Skip to content Skip to sidebar Skip to footer

Is It Safe To Modify An Array In For (..in..) Loop?

A = [1,2,3,4,5]; for (var i in A) { if (A[i] == 4) A.splice(i,1), A.push(7); if (A[i] == 2) A.splice(i,1), A.push(0); if (A[i] == 7) console.log('seven'); if (A[i]

Solution 1:

It's perfectly safe to change the object in the sense you won't get the browser complain about any change to the array. Just note that, in your example, it would still be valid behavior if you saw "seven, zero", just "seven", just "zero", or nothing at all being printed.

On the one hand, browsers must ensure that properties that are deleted, before being visited, are not enumerated. On the other hand, browsers are free to:

  • Enumerate new properties or let them out of the loop
  • Enumerate properties by any order.

That is why it is not safe to use for ... in to iterate arrays when you depend on the index/order. Indexes are treated as enumerable properties and can be enumerated with the same mechanics used for object's properties (where there is no expectation on the order of iteration).

Post a Comment for "Is It Safe To Modify An Array In For (..in..) Loop?"