如何快速清除JavaScript对象? [英] How to quickly clear a JavaScript Object?

查看:97
本文介绍了如何快速清除JavaScript对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript数组,我可以通过一次分配将其重置为空状态:

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 and ready to reuse, and as far as I understand is a single "operation" - that is, constant time.

是否有类似的方法来清除JS对象?我知道我可以迭代它的字段删除它们:

Is there a similar way to clear a JS Object? I know I can iterate its fields deleting them:

for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }

但这具有线性复杂性。

我也可以抛弃物体并创建一个新物体:

I can also just throw the object away and create a new one:

obj = {};

但是滥用新对象的创建会导致IE6上的垃圾收集问题。 (如此处所述

But "promiscuous" creation of new objects leads to problems with Garbage Collection on IE6. (As described here)

推荐答案

我认为对你的问题的简短回答是否定的(你可以创建一个新对象)。

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


  1. 在这个例子中,我认为将长度设置为0仍然会留下垃圾收集的所有元素。

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

你如果它是你经常使用的东西,可以将它添加到Object.prototype。是的,它的复杂性是线性的,但是之后不进行垃圾收集的任何东西都将是。

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.

这是最好的解决方案。我知道这与你的问题无关 - 但是我们需要多长时间才能继续支持IE6?有许多广告系列要停止使用它。

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.

这篇关于如何快速清除JavaScript对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆