我有点搞不懂JavaScript的删除操作符。以下面这段代码为例:

var obj = {
    helloText: "Hello World!"
};

var foo = obj;

delete obj;

执行这段代码后,obj为空,但foo仍然引用与obj完全相同的对象。我猜这个对象就是foo指向的那个对象。

这让我很困惑,因为我以为写delete obj删除的是obj在内存中所指向的对象——而不仅仅是变量obj。

这是因为JavaScript的垃圾收集器是在保留/释放的基础上工作的,所以如果我没有任何其他变量指向对象,它将从内存中删除?

(顺便说一下,我的测试是在Safari 4中完成的。)


当前回答

“隐式声明的变量”是全局对象的属性,所以删除对它们的作用就像对任何属性一样。用var声明的变量是不可破坏的。

其他回答

“隐式声明的变量”是全局对象的属性,所以删除对它们的作用就像对任何属性一样。用var声明的变量是不可破坏的。

如果你想根据对象的值删除它,可以这样做:

Object.keys(obj).forEach((key) => {
  if (obj[key] === "Hello World!") {
    delete obj[key];
  }
});

但是删除对象并不是一个好主意。设它为undefined,这样当你把它传递给一个参数时。它不会显示出来。无需删除。

Object.keys(obj).forEach((key) => {
  if (obj[key] === "Hello World!") {
    obj[key] = undefined;
  }
});

Setting a variable to null makes sure to break any references to objects in all browsers including circular references being made between the DOM elements and Javascript scopes. By using delete command we are marking objects to be cleared on the next run of the Garbage collection, but if there are multiple variables referencing the same object, deleting a single variable WILL NOT free the object, it will just remove the linkage between that variable and the object. And on the next run of the Garbage collection, only the variable will be cleaned.

除了GC问题之外,对于性能,应该考虑浏览器可能在后台执行的优化—>

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

这似乎是更好的空引用比删除它,因为这可能会改变幕后的'类' Chrome使用。

在java脚本中,delete不用于删除对象。

在本例中,用于删除对象键的Delete

var obj = { helloText: "Hello World!" }; 
var foo = obj;
delete obj;

对象没有被删除检查obj仍然使用相同的值删除用法:

delete obj.helloText

然后检查obj foo,都是空对象。