什么时候应该在JavaScript中使用delete vs设置元素为null? [英] When should I use delete vs setting elements to null in JavaScript?
问题描述
可能存在重复:
在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没有办法强制垃圾收集,而且你并不需要。 xy = null;
和删除xy;
都会消除 x
对前$
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.
如果你清空某个属性,它仍然被视为设置在对象上并且将被枚举。 / strong>我只能想到你更喜欢 delete
的地方是,如果你想枚举 x $ c的属性$ C>。
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
.
考虑以下几点:
Consider the following:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!