We can empty an arrary in Javascript in many ways.Lets go through each of the them.
For Example we have an array like this:
var myArray = ['a','b','c','d','e','f'];
First method :
myArray = []
Above code will empty the variable myArray and create a new empty array.but this is a wrong method to empty an array
Second method :
myArray.length = 0;
Above code will set the length of array equal to zero i.e it will empty the existing array but would not create another array.this method can be used when we want to update all reference variables pointing to pointing to.
Third method:
myArray.splice(0, myArray.length);
This method will also work same as the previous one and will update all the references pointing to the original array(myArray).
Fourth Method:
while(myArray.length){
myArray.pop();
}
The above can also empty arrays but it is not recommended to use this method often.
0 Comment(s)