問題描述
可能重復:
在 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模板網!