This question already has an answer here:
这个问题在这里已有答案:
- How to quickly clear a JavaScript Object? 7 answers
- 如何快速清除JavaScript对象? 7个答案
As stated Here, It seems that the most efficient way to empty an existing array (and NOT to allocate a new one) in javascript is to use:
如上所述,似乎在javascript中清空现有数组(而不是分配新数组)的最有效方法是使用:
array.length = 0;
Does the same operation work for plain objects? (aka "associative arrays" or "dictionaries") If not, what is the most efficient way to empty an existing javascript object?
相同的操作是否适用于普通对象? (又名“关联数组”或“字典”)如果没有,清空现有javascript对象的最有效方法是什么?
I think that allocating a new one is not the best option, since it will push some extra work to the garbage collector, and will allocate some new memory on the heap, but I might be wrong.
我认为分配一个新的不是最佳选择,因为它会将一些额外的工作推送到垃圾收集器,并将在堆上分配一些新内存,但我可能错了。
I need a solution that works at least with Chrome and Firefox.
我需要一个至少适用于Chrome和Firefox的解决方案。
1 个解决方案
#1
22
The shortest way to do that is to create a new object. You'd end up garbage collecting all the properties anyway.
最简单的方法是创建一个新对象。无论如何,你最终会收集所有属性的垃圾。
var foo = {
a: 5,
b: 4
};
foo = {};
You could also iterate over the properties and remove them individually:
您还可以迭代属性并单独删除它们:
for (var prop in foo) {
if (foo.hasOwnProperty(prop)) {
delete foo[prop];
}
}
It's also worth pointing out, as a matter of verbiage, that JavaScript has objects with properties, not associative arrays.
作为一个问题,值得指出的是JavaScript具有属性的对象,而不是关联数组。
#1
22
The shortest way to do that is to create a new object. You'd end up garbage collecting all the properties anyway.
最简单的方法是创建一个新对象。无论如何,你最终会收集所有属性的垃圾。
var foo = {
a: 5,
b: 4
};
foo = {};
You could also iterate over the properties and remove them individually:
您还可以迭代属性并单独删除它们:
for (var prop in foo) {
if (foo.hasOwnProperty(prop)) {
delete foo[prop];
}
}
It's also worth pointing out, as a matter of verbiage, that JavaScript has objects with properties, not associative arrays.
作为一个问题,值得指出的是JavaScript具有属性的对象,而不是关联数组。