可以说我已经在JavaScript中创建了一个对象及其属性,如下所示:
var obj = {};
obj['bar'] = 123;
obj['bar']['foo'] = new Array();
obj['bar']['xyz'] = new Array();
之后,我将元素推入两个数组。
如果我再写
delete obj['bar'];
两个数组也会被删除吗?
最佳答案
只要没有其他引用,它们将有资格进行垃圾回收。根据该代码,将不会有任何结果。何时以及是否真正清除它们取决于实现。
但是请注意,即使在删除bar
之前,它们也有资格使用GC,因为您的代码做得很奇怪。查看评论:
// Creates a blank object, so far so good.
var obj = {};
// Sets the `bar` property to the number 123.
obj['bar'] = 123;
// Retrieves the value of `bar` (the primitive number 123) and
// *converts* it into a `Number` instance (object), then
// creates a property on that object called `foo`, assigning a
// blank array to it. Because the Number object is never stored
// anywhere, both it and the array are IMMEDIATELY eligible for
// garbage collection. The value of `obj['foo']` is unaffected,
// it remains a primitive number.
obj['bar']['foo'] = new Array();
// The same happens again, a temporary Number instance and
// array are created, but both are IMMEDIATELY eligible for
// garbage collection; the value of `obj['bar']` is unaffected.
obj['bar']['xyz'] = new Array();
因此,您甚至不必删除
bar
,这些数组即刻可以进行垃圾回收。发生这种情况是因为在JavaScript中,数字是可以自动提升为Number
对象的基元-但不会影响分配给基元编号的属性的值。所以:var obj = {};
obj['bar'] = 123;
obj['bar']['foo'] = []; // [] is a better way to write new Array()
console.log(obj['bar']['foo']); // "undefined"
如果将
obj['bar'] =
行更改为:obj['bar'] = {};
要么
obj['bar'] = []; // Arrays are objects
...然后
foo
和xyz
属性不会立即消失,并且数组将一直存在,直到bar
被清除为止。