How to delete/unset the properties of a javascript object?

Possible Duplicates:
How to unset a Javascript variable?
How to remove a property from a javascript object

I'm looking for a way to remove/unset the properties of a JS 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 it's global object such as window , or using this in the outermost scope ie

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

http://perfectionkills.com/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 array's 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 so:

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

链接地址: http://www.djcxy.com/p/4666.html

上一篇: 删除Javascript中的属性

下一篇: 如何删除/取消设置JavaScript对象的属性?