javascript - Delete object/associative array -
lets have created object , properties in javascript follows-
var obj = {}; obj['bar'] = 123; obj['bar']['foo'] = new array(); obj['bar']['xyz'] = new array();
after this, push elements 2 arrays. if write
delete obj['bar'];
will 2 arrays deleted ?
will 2 arrays deleted ?
they'll eligible garbage collection, assuming nothing else has references them. , nothing will, based on code. when , whether they're actually cleaned up implementation.
but note they're eligible gc before remove bar
, because code doing quite odd. see comments:
// creates blank object, far good. var obj = {}; // sets `bar` property number 123. obj['bar'] = 123; // retrieves value of `bar` (the primitive number 123) , // *converts* `number` instance (object), // creates property on object called `foo`, assigning // blank array it. because number object never stored // anywhere, both , array eligible // garbage collection. value of `obj['foo']` unaffected, // remains primitive number. obj['bar']['foo'] = new array(); // same happens again, temporary number instance , // array created, both eligible // garbage collection; value of `obj['bar']` unaffected. obj['bar']['xyz'] = new array();
so didn't have remove bar
, arrays instantly eligible garbage collection. happens because in javascript, numbers primitives can automatically promoted number
objects — doesn't affect value of property primitive number assigned to. so:
var obj = {}; obj['bar'] = 123; obj['bar']['foo'] = []; // [] better way write new array() console.log(obj['bar']['foo']); // "undefined"
if change obj['bar'] =
line to:
obj['bar'] = {};
or
obj['bar'] = []; // arrays objects
...then foo
, xyz
properties not instantly disappear, , arrays stick around until bar
cleaned up.
Comments
Post a Comment