Way 1,splice
1 2 3 |
var ary = [1,2,3,4]; Ary.splice (0,ary.length); Console.log (ary); The output [], an empty array, is emptied |
method 2,length assignment to 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 be an error, compile pass. And JS can, and empty the array,
1 2 3 |
var ary = [1,2,3,4]; ary.length = 0; Console.log (ary); The output [], an empty array, is emptied |
The current prototype the array's clear and the empty of the array in the MooTools library use this way to empty the array.
mode 3, assigned to []
1 2 |
var ary = [1,2,3,4]; ary = []; Assignment to an empty array to empty the original array |
This is not really a strictly clear empty array, just ary the value to an empty array, and the previous array will wait for garbage collection if no reference is directed at it.
The EXT Library Ext.compositeelementlite class's clear is emptied using this method.
Mode 2 preserves the other attributes of the array, and mode 3 is not retained. A lot of people think that Mode 2 is more efficient because it only assigns length to the value, and mode 3 builds the object again. The test is precisely the way 3 efficiency is high. 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: Mode 3 faster, more efficient. So if you don't keep the other attributes of the original array, the way you use it is more recommended.