Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  5] [ 2]  / answers: 1 / hits: 126065  / 13 Years ago, sun, june 26, 2011, 12:00:00

Possible Duplicates:

How can I unset a JavaScript variable?

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


More From » jquery

 Answers
142

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

[#91492] Friday, June 24, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brockg

Total Points: 55
Total Questions: 104
Total Answers: 104

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;