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

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

var foo = obj;

delete obj;

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

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

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

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


当前回答

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

其他回答

在寻找同样的答案时,我偶然发现了这篇文章。我最终所做的只是弹出obj.pop()我的对象中所有存储的值/对象,这样我就可以重用对象。不知道这是不是不好的做法。这个技巧在我用Chrome Dev工具或FireFox Web Console测试代码时派上了用场。

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.

delete操作符从数组中删除对象、对象的属性或元素。操作符还可以删除未使用var语句声明的变量。 在下面的例子中,'fruits'是一个声明为var的数组,并被删除了(真的吗??)

delete objectName
delete objectName.property
delete objectName[index] 
delete property // The command acts  only within a with statement.

var fruits = new Array("Orange", "Apple", "Banana", "Chery");
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("Fruits List : " + fruits);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);
//Delete the array object.
delete fruits;
var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode("Display the Fruits after delete the array object - Fruits List : "+ fruits;); 
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);

https://www.w3resource.com/javascript/operators/delete.php

刚刚找到一个jsperf,你可能认为有趣的在这个问题上。(把它放在周围可以方便地完成图片)

它比较了delete、设置null和设置undefined。

但请记住,当您多次删除/设置属性时,它会测试情况。

这对我很有用,尽管这不是一个好的练习。它简单地删除所有的 对象所属的关联元素。

 for (element in homeService) {
          delete homeService[element];
  }