我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?

When should I use delete vs setting elements to null in JavaScript?(我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?)
本文介绍了我什么时候应该在 JavaScript 中使用 delete vs 将元素设置为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

可能重复:
在 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; 都消除了 xy 之前值的引用.该值将在必要时被垃圾回收.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)