可能重复:
在 JavaScript 中删除对象
我有一个具有大量属性的 JS 对象.如果我想强制浏览器垃圾收集这个对象,我需要将这些属性中的每一个都设置为 null 还是需要使用 delete 运算符?两者有什么区别?
I have a JS object having a large number of properties. If I want to force the browser to garbage collect this object, do I need to set each of these properties as null or do I need to use the delete operator? What's the difference between the two?
在 JavaScript 中没有强制垃圾回收的方法,你也不需要这样做.x.y = null;
和 delete x.y;
都消除了 x
对 y
之前值的引用.该值将在必要时被垃圾回收.
There is no way to force garbage collection in JavaScript, and you don't really need to. x.y = null;
and delete x.y;
both eliminate x
's reference to the former value of y
. The value will be garbage collected when necessary.
如果您将某个属性设为空,它仍会被视为对象上的设置"并会被枚举.我唯一能想到您希望在哪里delete
是如果您要枚举 x
的属性.
If you null out a property, it is still considered 'set' on the object and will be enumerated. The only time I can think of where you would prefer delete
is if you were going to enumerate over the properties of x
.
考虑以下几点:
var foo = { 'a': 1, 'b': 2, 'c': 3 };
console.log('Deleted a.');
delete foo.a
for (var key in foo)
console.log(key + ': ' + foo[key]);
console.log('Nulled out b.');
foo['b'] = null;
for (var key in foo)
console.log(key + ': ' + foo[key]);
此代码将产生以下输出:
This code will produce the following output:
Deleted a.
b: 2
c: 3
Nulled out b.
b: null
c: 3
这篇关于我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!