Suppose I have this code:
var myArray = new Object(); myArray["firstname"] = "Bob"; myArray["lastname"] = "Smith"; myArray["age"] = 25;
Now if I wanted to remove "lastname"?….is there some equivalent of myArray["lastname"].remove()?
(I need the element gone because the number of elements is important and I want to keep things clean.)
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the
deleteoperator:Note that when
deleteis applied to an index property of anArray, you will create a sparsely populated array (ie. an array with a missing index).When working with instances of
Array, if you do not want to create a sparsely populated array – and you usually don’t – then you should useArray#spliceorArray#pop.Note that the
deleteoperator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an objecto, thenowill subsequently be garbage collected in the normal way.Using the
deleteoperator can affect JavaScript engines’ ability to optimise code.