javascript - Is it safe to modify an Array in for (..in..) loop? -
a = [1,2,3,4,5]; (var 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] == 0) console.log('zero'); } console.log(a);
this seems work, not know details of implementation of for(..in..) loop sure safe in conditions.
it's safe change object in sense won't browser complain change array. note that, in example, still valid behavior if saw "seven, zero", "seven", "zero", or nothing @ being printed.
on 1 hand, browsers must ensure properties deleted, before being visited, not enumerated. on other hand, browsers free to:
- enumerate new properties or let them out of loop
- enumerate properties order.
that why not safe use for ... in
iterate arrays when depend on index/order. indexes treated enumerable properties , can enumerated same mechanics used object's properties (where there no expectation on order of iteration).
Comments
Post a Comment