Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
30
rated 0 times [  33] [ 3]  / answers: 1 / hits: 23191  / 12 Years ago, sun, march 3, 2013, 12:00:00

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:



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?



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.


More From » arrays

 Answers
3

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.


[#79874] Friday, March 1, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
mitchellg questions
Sun, Jan 10, 21, 00:00, 3 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
Fri, Jul 10, 20, 00:00, 4 Years ago
;