Best way to deallocate an array of array in javascript

and*_*ias 6 javascript

What is the best way to deallocate an array of array in javascript to make sure no memory leaks will happen?

var foo = new Array();
foo[0] = new Array();
foo[0][0] = 'bar0';
foo[0][1] = 'bar1';
foo[1] = new Array();
...
Run Code Online (Sandbox Code Playgroud)
  1. delete(foo)?
  2. iterate through foo, delete(foo[index]) and delete(foo)?
  3. 1 and 2 give me the same result?
  4. none?

Nic*_*itz 8

foo = null;
Run Code Online (Sandbox Code Playgroud)

应该足以让垃圾收集器摆脱数组,包括它的所有子数组(假设没有别的引用它们).请注意,它只会在它想要时,而不是立即消除它,所以如果浏览器的内存消耗不会立即消失,不要感到惊讶:这不是泄漏.

如果这些数组元素中的任何一个包含对DOM节点的引用,则可能会变得更复杂.

  • 对于那些在2014年访问这里的人,请注意,几乎没有理由将某些内容设置为null或尝试"解除分配"它(JS中不存在的概念),或者做任何其他事情来让GC做任何事情.它本身就很好,非常感谢你. (2认同)

Lau*_*uri 2

您无法删除变量,请将其设置为空foo = null;

..或使用命名空间对象

var namespace = {};
namespace.foo = [];
delete namespace.foo;
Run Code Online (Sandbox Code Playgroud)