Saturday 15 June 2019

jquery - 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?


Answer



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

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...