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

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

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?

回答1:

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 i.e

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"] 


回答2:

To blank it:

myObject["myVar"]=null; 

To remove it:

delete myObject["myVar"] 

as you can see in duplicate answers



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!