How to quickly clear a JavaScript Object?

后端 未结 8 1078
一个人的身影
一个人的身影 2020-11-27 12:52

With a JavaScript Array, I can reset it to an empty state with a single assignment:

array.length = 0;

This makes the Array \"appear\" empty

相关标签:
8条回答
  • 2020-11-27 13:26

    The short answer to your question, I think, is no (you can just create a new object).

    1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.

    2. You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.

    3. This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.

    Feel free to correct me if there's anything incorrect above.

    0 讨论(0)
  • 2020-11-27 13:28

    Well, at the risk of making things too easy...

    for (var member in myObject) delete myObject[member];
    

    ...would seem to be pretty effective in cleaning the object in one line of code with a minimum of scary brackets. All members will be truly deleted instead of left as garbage.

    Obviously if you want to delete the object itself, you'll still have to do a separate delete() for that.

    0 讨论(0)
提交回复
热议问题