最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json - How to delete full object with javascript? - Stack Overflow

programmeradmin4浏览0评论

I tried it, but delete doesn't work.

var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};

alert(x.y);
delete x;

alert(x.y); // still shows '42'

How to delete the full object crossbrowser?

Edit: x = null also doesn't work

I tried it, but delete doesn't work.

var x = {"y":42,"z":{"a":1,"b":[1,2,3]}};

alert(x.y);
delete x;

alert(x.y); // still shows '42'

How to delete the full object crossbrowser?

Edit: x = null also doesn't work

Share Improve this question edited Aug 21, 2015 at 15:40 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 3, 2012 at 21:10 Danny FoxDanny Fox 40.7k29 gold badges71 silver badges96 bronze badges 2
  • Would be a good idea to mention in which browsers it doesn't work... – ThiefMaster Commented Apr 3, 2012 at 21:12
  • 1 what do you mean x = null doesn't work? If you are referring to accessing it, x.y will most certainly fail after assigning null to x. If you are referring to reclaiming memory, then the object that was assigned to x will be cleaned up by garbage collection, if there are no other references to it – Matt Commented Apr 3, 2012 at 21:23
Add a comment  | 

6 Answers 6

Reset to default 6

You can only use the delete operator to delete variables declared implicitly, but not those declared with var. You can set x = null or x = undefined

You don't need to delete objects in JavaScript. The object will be garbage collected after all references to it are removed. To remove the reference, use:

x = null;

You cannot delete a variable or a function. Only a property of an object. You can simply assign:

x = null;

if you want to clear its value.

UPDATE: clarification regarding functions:

>> function f1() {console.log("aa");}
>> f1();
aa
>> delete f1;
false
>> f1();
aa

But if you declare a global function as a window attribute, you can delete it:

>> f1 = f1() {console.log("aa");}
>> delete window.f1;
true

The same is for variables:

>> a = "x";
>> console.log(a);
x
>> delete window.a;
true
>> console.log(a);
ReferenceError: a is not defined

But:

>> var a = "x";
>> console.log(a);
x
>> delete a;
false
>> console.log(a);
x

You can't delete an object from the global namespace in Javascript.

You can delete objects within x, but not x itself.

Try x = null; or x = undefined;.

You probably set object with const instead of var

发布评论

评论列表(0)

  1. 暂无评论