Way 1,splice
1
2
3
var ary = [1,2,3,4];
Ary.splice (0,ary.length);
Console.log (ary); Output [], empty array, is emptied
Method 2,length is assigned a value of 0
This is interesting, and other languages such as Java, whose array length is read-only, cannot be assigned a value. Such as
1
2
int[] ary = {1,2,3,4};
ary.length = 0;
Java will error, compile pass. And JS can be, and the array is emptied,
1
2
3
var ary = [1,2,3,4];
ary.length = 0;
Console.log (ary); Output [], empty array, is emptied
The current prototype array in the clear and MooTools libraries in the empty array is used this way to empty the array.
Mode 3, assigned to []
1
2
var ary = [1,2,3,4];
ary = []; Assign to an empty array to clear the original array
In fact, this is not a strict meaning of the empty array, just the ARY is re-assigned to an empty array, before the array if there is no reference to it will wait for garbage collection.
The clear of the EXT library Ext.compositeelementlite class is cleared using this method.
Mode 2 retains the other properties of the array, and mode 3 is not preserved. Many people think that Mode 2 is more efficient because it simply re-assigns a value to length, and mode 3 re-establishes the object. The test is precisely the efficiency of mode 3. Test code:
1
2
3
4
5
6
7
8
9
var a = [];
for (var i=0; i< 1000000; i++) {
A.push (i);
}
var start = new Date ();
a = [];
a.length = 0;
var end = new Date ();
alert (End-start);
Test results:
The above results can be seen: 3 faster and more efficient. Therefore, if you do not preserve the other properties of the original array, the method of ext is more recommendable.
Three ways to empty an array in JavaScript