When should I use delete vs setting elements to null in JavaScript?(我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?)
问题描述
可能重复:
在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?


- 失败的 Canvas 360 jquery 插件 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07