开发者

How can I delete/unset the properties of a JavaScript object? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

How can I unset a JavaScript variable?

Ho开发者_开发知识库w do I remove a property from a JavaScript object?

I'm looking for a way to remove/unset the properties of a JavaScript object, so they'll no longer come up if I loop through the object doing for (var i in myObject). How can this be done?


Simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

But if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

But if you do wish to delete variables in the global namespace, you can use its global object such as window, or using this in the outermost scope, i.e.,

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

Understanding delete

Another fact is that using delete on an array will not remove the index, but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity. When it comes to arrays you should use splice which is a prototype of the array object.

Example Array:

var myCars = new Array();
myCars[0] = "Saab";
myCars[1] = "Volvo";
myCars[2] = "BMW";

If I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

But using splice like

myCars.splice(1,1);

would result in:

["Saab", "BMW"]


To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜