Sunday, October 30, 2016

Remove/Delete Properties from Javascript Object

Simplest way is to 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
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();
if I was to do:
delete myCars[1];
the resulting array would be:
["Saab", undefined, "BMW"]
but using splice like so:
would result in:
["Saab", "BMW"]

No comments:
Write comments
Recommended Posts × +