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?
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
